How to concatenate multiple lines of output to one line?

T. Webster picture T. Webster · Mar 22, 2013 · Viewed 247k times · Source

If I run the command cat file | grep pattern, I get many lines of output. How do you concatenate all lines into one line, effectively replacing each "\n" with "\" " (end with " followed by space)?

cat file | grep pattern | xargs sed s/\n/ /g isn't working for me.

Answer

Chris Seymour picture Chris Seymour · Mar 22, 2013

Use tr '\n' ' ' to translate all newline characters to spaces:

$ grep pattern file | tr '\n' ' '

Note: grep reads files, cat concatenates files. Don't cat file | grep!

Edit:

tr can only handle single character translations. You could use awk to change the output record separator like:

$ grep pattern file | awk '{print}' ORS='" '

This would transform:

one
two 
three

to:

one" two" three"