I have a file, from which I want to retrieve the first column, and add a comma between each value.
Example:
AAAA 12345 xccvbn
BBBB 43431 fkodks
CCCC 51234 plafad
to obtain
AAAA,BBBB,CCCC
I decided to use awk, so I did
awk '{ $1=$1","; print $1 }'
Problem is: this add a comma also on the last value, which is not what I want to achieve, and also I get a space between values.
How do I remove the comma on the last element, and how do I remove the space? Spent 20 minutes looking at the manual without luck.
This is the shortest I know
In this case, as simple cut and paste solution
This can be very simple like this:
awk -F',' '{print $1","$1","$2","$3}' inputFile
where input file is :
1,2,3 2,3,4
etc.Surpised that no one is using OFS (output field separator). Here is probably the simplest solution that sticks with awk and works on Linux and Mac: use "-v OFS=," to output in comma as delimiter:
$ echo '1:2:3:4' | awk -F: -v OFS=, '{print $1, $2, $4, $3}' generates: 1,2,4,3
It works for multiple char too: $ echo '1:2:3:4' | awk -F: -v OFS=., '{print $1, $2, $4, $3}' outputs: 1.,2.,4.,3