How to concatenate multiple lines of output to one line?

前端 未结 11 1363
失恋的感觉
失恋的感觉 2020-12-04 07:08

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

相关标签:
11条回答
  • 2020-12-04 07:38

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

    echo $(cat file)
    
    0 讨论(0)
  • 2020-12-04 07:40

    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.

    0 讨论(0)
  • 2020-12-04 07:43

    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" 
    
    0 讨论(0)
  • 2020-12-04 07:44

    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
    
    0 讨论(0)
  • 2020-12-04 07:45

    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

    0 讨论(0)
  • 2020-12-04 07:45

    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
    
    0 讨论(0)
提交回复
热议问题