用逗号分隔(perl / sed / awk)[ duplicate ]将多行转换为一行

用逗号分隔(perl / sed / awk)[ duplicate ]将多行转换为一行

问题描述:

This question already has an answer here:

I have the following data in multiple lines:

foo
bar
qux
zuu
sdf
sdfasdf

What I want to do is to convert them with one line and comma separated:

foo,bar,qux,zuu,sdf,sdfasdf

What's the best unix one-liner to do that?

</div>

转载于:https://stackoverflow.com/questions/15758814/turning-multiple-lines-into-one-line-with-comma-separated-perl-sed-awk

Using paste command:

paste -d, -s file

There are many ways it can be achieved. The tool you use mostly depends on your own preference or experience.

Using tr command:

tr '\n' ',' < somefile

Using awk:

awk -F'\n' '{if(NR == 1) {printf $0} else {printf ","$0}}' somefile

Perl one-liner:

perl -pe'chomp, s/$/,/ unless eof' file

or, if you want to be more cryptic:

perl '-peeof||chomp&&s/$/,/' file

based on your input example, this awk line works. (without trailing comma)

awk -vRS="" -vOFS=',' '$1=$1' file

test:

kent$  echo "foo
bar
qux
zuu
sdf
sdfasdf"|awk -vRS="" -vOFS=',' '$1=$1' 
foo,bar,qux,zuu,sdf,sdfasdf

perl -pi.bak -e 'unless(eof){s/\n/,/g}' your_file

This will create a backup of original file with an extension of .bak and then modifies the original file

sed -n 's/.*/&,/;H;$x;$s/,\n/,/g;$s/\n\(.*\)/\1/;$s/\(.*\),/\1/;$p'

file

aaa
bbb
ccc
ddd

xargs

cat file | xargs

result

aaa bbb ccc ddd 

xargs improoved

cat file | xargs | sed -e 's/ /,/g'

result

aaa,bbb,ccc,ddd 

xargs -a your_file | sed 's/ /,/g'

this is more shorter way