簡體   English   中英

當 \n 文本沒有被 bash 打斷時,如何將 pipe 和 output 轉換為 printf?

[英]How to pipe an output to printf, when the \n text is not being breaken by bash?

我有這樣的文字:

"while compiling ejs\n\nIf the above error is not helpful, you may want to try EJS-Lint:\nhttps://github.com/RyanZim/EJS-Lint%5CnOr, if you meant to create an async function, pass `async: true` as an option.","stack":"SyntaxError: (...)"

在 bash 中沒有被分成幾行(運行npm run Script

我如何將 pipe 轉換為 printf 或任何工具,以使 \n 實際呈現為斷線?

我嘗試在管道文本上查看多個來源,以使 bash 將字符串 \n 讀入實際上是一個換行符,但沒有成功。

我希望 '\n' 實際上會換行。

解決方案:

正如@Charles Duffy 指出的那樣,

npm run Script | while IFS= read -r line; do printf '%b\n' "$line"; done

作品。 最終的 output 看起來像這樣,以提供更多的關閉:

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: true` as an option.
    at new Function (<anonymous>)
    at Template.compile (<ommited-path>/node_modules/ejs/lib/ejs.js:673:12)
    at Object.compile (<ommited-path>/node_modules/ejs/lib/ejs.js:398:16)

一個while read循環來收集行,然后將它們放入printf %b進行格式化應該做你想做的:

npm run Script | while IFS= read -r line; do printf '%b\n' "$line"; done

BashFAQ #1中記錄了此處使用的一般模式。 一些注意事項:

  • 此管道的退出狀態將是while循環的退出狀態,除非您先運行set -o pipefail使管道中的任何位置發生故障導致整個命令報告故障。
  • 使用IFS=阻止刪除輸入前面或結尾的空格。
  • 在定義line變量之前,使用-r會阻止反斜杠被read本身刪除。
  • printf '%b\n'是 bash 以非標准方式實現的POSIX 建議的替代方案,如echo -e (請參閱鏈接的“應用程序使用”部分; Why is printf better than echo的答案中也有具體示例 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM