将多个行转换为一个逗号分隔的行

我有以下多行数据:

foo
bar
qux
zuu
sdf
sdfasdf

我要做的是把它们转换成一个逗号分隔的行:

foo,bar,qux,zuu,sdf,sdfasdf

最好的 unix 俏皮话是什么?

157578 次浏览

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 a shorter way.