How to concatenate multiple lines of output to one line?

前端 未结 11 1364
失恋的感觉
失恋的感觉 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:52

    The fastest and easiest ways I know to solve this problem:

    When we want to replace the new line character \n with the space:

    xargs < file
    

    xargs has own limits on the number of characters per line and the number of all characters combined, but we can increase them. Details can be found by running this command: xargs --show-limits and of course in the manual: man xargs

    When we want to replace one character with another exactly one character:

    tr '\n' ' ' < file
    

    When we want to replace one character with many characters:

    tr '\n' '~' < file | sed s/~/many_characters/g
    

    First, we replace the newline characters \n for tildes ~ (or choose another unique character not present in the text), and then we replace the tilde characters with any other characters (many_characters) and we do it for each tilde (flag g).

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

    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)

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

    Here is another simple method using awk:

    # cat > file.txt
    a
    b
    c
    
    # cat file.txt | awk '{ printf("%s ", $0) }'
    a b c
    

    Also, if your file has columns, this gives an easy way to concatenate only certain columns:

    # cat > cols.txt
    a b c
    d e f
    
    # cat cols.txt | awk '{ printf("%s ", $2) }'
    b e
    
    0 讨论(0)
  • 2020-12-04 07:59

    Here is the method using ex editor (part of Vim):

    • Join all lines and print to the standard output:

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

      $ ex +%j -scwq file
      

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

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

    Probably the best way to do it is using 'awk' tool which will generate output into one line

    $ awk ' /pattern/ {print}' ORS=' ' /path/to/file
    

    It will merge all lines into one with space delimiter

    0 讨论(0)
提交回复
热议问题