使用awk打印列,并添加逗号 [英] use awk to print a column, adding a comma

查看:940
本文介绍了使用awk打印列,并添加逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,我想从该文件中检索第一列,并在每个值之间添加一个逗号.

I have a file, from which I want to retrieve the first column, and add a comma between each value.

示例:

AAAA 12345 xccvbn
BBBB 43431 fkodks
CCCC 51234 plafad

获得

AAAA,BBBB,CCCC

我决定使用awk,所以我做了

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.

如何删除最后一个元素上的逗号,以及如何删除空格?花了20分钟查看手册,没有运气.

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 '{printf "%s%s",sep,$1; sep=","} END{print ""}' file
AAAA,BBBB,CCCC

或者,如果您愿意:

$ 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

这篇关于使用awk打印列,并添加逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆