简体   繁体   中英

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

I have text like this:

"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: (...)"

Which is NOT being broken into lines in bash (running a npm run Script )

How can I pipe it into printf, or whatever tool, to make \n to be actually rendered as a break-line?

I tried viewing multiple sources on piping text to make bash read the string \n into actually a linebreak, but unsucessefully.

I expect '\n' to actually break lines.

SOLUTION:

As @Charles Duffy pointed out,

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

works. The final output looks like these, to give more closure:

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)

A while read loop to collect lines and then put them into printf %b for formatting should do what you want:

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

The general pattern used here is documented in BashFAQ #1 . Some notes:

  • The exit status of this pipeline will be that of the while loop, unless you run set -o pipefail first to make a failure anywhere in a pipeline cause the entire command to report a failure.
  • Using IFS= stops spaces at the front or end of the input from being deleted.
  • Using -r stops backslashes from being removed by read itself before the line variable is defined.
  • printf '%b\n' is the POSIX-advised alternative to what bash implements in a nonstandard way as echo -e (see the APPLICATION USAGE section of the link; there are also concrete examples in the answer to Why is printf better than echo? ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM