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

前端 未结 9 1927
囚心锁ツ
囚心锁ツ 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:01

    This sed one-line should work -

    sed -e :a -e 'N;s/\n/,/;ba' file

    Test:

    [jaypal:~/Temp] cat file
    foo
    bar
    baz
    
    [jaypal:~/Temp] sed -e :a -e 'N;s/\n/,/;ba' file
    foo,bar,baz
    

    To handle empty lines, you can remove the empty lines and pipe it to the above one-liner.

    sed -e '/^$/d' file | sed -e :a -e 'N;s/\n/,/;ba'
    

提交回复
热议问题