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

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

    Perl:

    cat data.txt | perl -pe 'if(!eof){chomp;$_.=","}'
    

    or yet shorter and faster, surprisingly:

    cat data.txt | perl -pe 'if(!eof){s/\n/,/}'
    

    or, if you want:

    cat data.txt | perl -pe 's/\n/,/ unless eof'
    

提交回复
热议问题