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:42
awk {'print $1","$2","$3'} file_name

This is the shortest I know

查看更多
ら.Afraid
3楼-- · 2020-07-11 07:45

In this case, as simple cut and paste solution

cut -d" " -f1 file | paste -s -d,
查看更多
该账号已被封号
4楼-- · 2020-07-11 07:45

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.

查看更多
家丑人穷心不美
5楼-- · 2020-07-11 07:50

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

查看更多
登录 后发表回答