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.
In case somebody as me wants to use awk for cleaning docker images:
It says: If it is first line only print first field, for the other lines first print
,
then print first field.Output:
Why make it complicated :) (as long as file is not too large)
For better porability.
You can do this:
a++ is interpreted as a condition. In the first row its value is 0, so the comma is not added.
EDIT: If you want a newline, you have to add
END{printf "\n"}
. If you have problems reading in the file, you can also try:or if you prefer:
or if you like golf and don't mind it being inefficient for large files:
Using Perl