如何让Bash中含\n的非换行文本通过管道转为实际换行格式?
我太懂这种烦恼了!之前运行npm脚本时,输出里的\n字符完全不生效,所有内容挤成一团,读起来特别费劲——就像你遇到的这种情况:
while compiling ejs\n\nIf the above error is not helpful, you may want to try EJS-Lint:\nhttps://github.com/RyanZim/EJS-Lint\nOr, if you meant to create an async function, pass
async: trueas an option.","stack":"SyntaxError: (...)"
找了好多种方法尝试把这些\n转成实际换行都没成功,后来终于找到靠谱的解决方案啦:
直接用下面的命令管道处理就行:
npm run Script | while IFS= read -r line; do printf '%b\n' "$line"; done
原理其实很简单:printf '%b'会自动解析字符串里的转义字符,把\n转换成真正的换行;而while IFS= read -r line则是安全地逐行读取npm脚本的输出,避免出现内容截断或者转义丢失的问题。
处理后的输出就会变成清晰的换行格式,比如:
If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass
async: trueas an option.at new Function (
) at Template.compile (
/node_modules/ejs/lib/ejs.js:673:12) at Object.compile (
/node_modules/ejs/lib/ejs.js:398:16)
备注:内容来源于stack exchange,提问作者Pedro Gomes Branquinho Facti

