use awk to print a column, adding a comma

2020-07-11 07:02发布

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.

标签: awk
10条回答
乱世女痞
2楼-- · 2020-07-11 07:28

In case somebody as me wants to use awk for cleaning docker images:

docker image ls | grep tag_name | awk '{print $1":"$2}'
查看更多
手持菜刀,她持情操
3楼-- · 2020-07-11 07:30
awk 'NR==1{printf "%s",$1;next;}{printf "%s%s",",",$1;}' input.txt

It says: If it is first line only print first field, for the other lines first print , then print first field.

Output:

AAAA,BBBB,CCCC
查看更多
在下西门庆
4楼-- · 2020-07-11 07:34

Why make it complicated :) (as long as file is not too large)

awk '{a=NR==1?$1:a","$1} END {print a}' file
AAAA,BBBB,CCCC

For better porability.

awk '{a=(NR>1?a",":"")$1} END {print a}' file
查看更多
聊天终结者
5楼-- · 2020-07-11 07:35

You can do this:

awk 'a++{printf ","}{printf "%s", $1}' file

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:

cat file | awk 'a++{printf ","}{printf "%s", $1}'
查看更多
啃猪蹄的小仙女
6楼-- · 2020-07-11 07:36
$ awk '{printf "%s%s",sep,$1; sep=","} END{print ""}' file
AAAA,BBBB,CCCC

or if you prefer:

$ awk '{printf "%s%s",(NR>1?",":""),$1} END{print ""}' file
AAAA,BBBB,CCCC

or if you like golf and don't mind it being inefficient for large files:

$ awk '{r=r s $1;s=","} END{print r}' file
AAAA,BBBB,CCCC
查看更多
闹够了就滚
7楼-- · 2020-07-11 07:42

Using Perl

$ cat group_col.txt
AAAA 12345 xccvbn
BBBB 43431 fkodks
CCCC 51234 plafad

$ perl -lane ' push(@x,$F[0]); END { print join(",",@x) } ' group_col.txt
AAAA,BBBB,CCCC

$
查看更多
登录 后发表回答