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
In bash echo without quotes remove carriage returns, tabs and multiple spaces
echo $(cat file)
On red hat linux I just use echo :
echo $(cat /some/file/name)
This gives me all records of a file on just 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:
one
two
three
to:
one" two" three"
This is an example which produces output separate by commas. You can replace the comma by whatever separator you need.
cat <<EOD | xargs | sed 's/ /,/g'
> 1
> 2
> 3
> 4
> 5
> EOD
produces:
1,2,3,4,5
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.
grep xargs
I like the xargs solution, but if it's important to not collapse spaces, then one might instead do:
sed ':b;$!{N;bb};s/\n/ /g'
That will replace newlines for spaces, without substituting the last line terminator like tr '\n' ' ' would.
This also allows you to use other joining strings besides a space, like a comma, etc, something that xargs cannot do:
$ seq 1 5 | sed ':b;$!{N;bb};s/\n/,/g'
1,2,3,4,5