The paste command can merge lines from multiple input files. By default, it merges lines in a way that entries in the first column belong to the first file, those in the second column are for the second file, and so on. The -s option can let it merge lines row-wise.
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"
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
In bash echo
without quotes remove carriage returns, tabs and multiple spaces
echo $(cat file)
This could be what you want
cat file | grep pattern | paste -sd' '
As to your edit, I'm not sure what it means, perhaps this?
cat file | grep pattern | paste -sd'~' | sed -e 's/~/" "/g'
(this assumes that ~
does not occur in file
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With