Concise and portable “join” on the Unix command-line

前端 未结 9 1902
囚心锁ツ
囚心锁ツ 2020-11-29 00:53

How can I join multiple lines into one line, with a separator where the new-line characters were, and avoiding a trailing separator and, optionally, ignoring empty lines?

相关标签:
9条回答
  • 2020-11-29 01:15

    Perhaps a little surprisingly, paste is a good way to do this:

    paste -s -d","
    

    This won't deal with the empty lines you mentioned. For that, pipe your text through grep, first:

    grep -v '^$' | paste -s -d"," -
    
    0 讨论(0)
  • 2020-11-29 01:16

    How about to use xargs?

    for your case

    $ cat foo.txt | sed 's/$/, /' | xargs
    

    Be careful about the limit length of input of xargs command. (This means very long input file cannot be handled by this.)

    0 讨论(0)
  • 2020-11-29 01:21

    My answer is:

    awk '{printf "%s", ","$0}' foo.txt
    

    printf is enough. We don't need -F"\n" to change field separator.

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