Turning multiple lines into one comma separated line
LinuxPerlUnixSedAwkLinux Problem Overview
I have the following data in multiple lines:
foo
bar
qux
zuu
sdf
sdfasdf
What I want to do is to convert them to one comma separated line:
foo,bar,qux,zuu,sdf,sdfasdf
What's the best unix one-liner to do that?
Linux Solutions
Solution 1 - Linux
Using paste command:
paste -d, -s file
Solution 2 - Linux
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
Solution 3 - Linux
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
Solution 4 - Linux
xargs -a your_file | sed 's/ /,/g'
This is a shorter way.
Solution 5 - Linux
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
Solution 6 - Linux
Perl one-liner:
perl -pe'chomp, s/$/,/ unless eof' file
or, if you want to be more cryptic:
perl '-peeof||chomp&&s/$/,/' file
Solution 7 - Linux
sed -n 's/.*/&,/;H;$x;$s/,\n/,/g;$s/\n\(.*\)/\1/;$s/\(.*\),/\1/;$p'
Solution 8 - Linux
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