How to concatenate multiple lines of output into one line?

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

cat file | grep pattern | xargs sed s/\n/ /g cat file | grep pattern | xargs sed s/\n/ /g does not work for me.

+44
linux unix bash grep tr
Mar 22 '13 at 21:27
source share
5 answers

Use tr '\n' ' ' to translate all newlines to spaces:

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

Note: grep reads files, cat merges files. Not cat file | grep cat file | grep !

Edit:

tr can only handle single character translations. You can use awk to change the output record separator, for example:

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

This will change:

 one two three 

at

 one" two" three" 
+86
Mar 22 '13 at 21:31
source share

The pipeline output on xargs combines each line of output into one line with spaces:

 grep pattern file | xargs 

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

grep xargs

+27
Aug 11 '14 at 20:35
source share

In bash echo without quotes, remove quotes, tabs and a few spaces

 echo $(cat file) 
+18
Nov 05 '15 at 9:11
source share

It may be what you want

 cat file | grep pattern | paste -sd' ' 

As for your editing, I'm not sure what that means, maybe it?

 cat file | grep pattern | paste -sd'~' | sed -e 's/~/" "/g' 

(this assumes ~ not found in file )

+13
Mar 22 '13 at 21:41
source share

Here is a method using the ex editor:

  • J for all lines and p rint for standard output:

     $ ex +%j +%p -scq! file 
  • J in all lines in place (in a file):

     $ ex +%j -scwq file 

    Note. This will concatenate all the lines inside the it-self file!

+2
Dec 20 '16 at 22:19
source share



All Articles