How to concatenate multiple lines of output to one line?

前端 未结 11 1369
失恋的感觉
失恋的感觉 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).

提交回复
热议问题