How to concatenate multiple lines of output to one line? How to concatenate multiple lines of output to one line? unix unix

How to concatenate multiple lines of output to one line?


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:

onetwo three

to:

one" two" three" 


Piping output to xargs will concatenate each line of output to a single line with spaces:

grep pattern file | xargs

Or any command, eg. ls | xargs. The default limit of xargs output is ~4096 characters, but can be increased with eg. xargs -s 8192.


In bash echo without quotes remove carriage returns, tabs and multiple spaces

echo $(cat file)