添加列使用awk。有什么不对这个awk命令? [英] Adding columns with awk. What is wrong with this awk command?

查看:87
本文介绍了添加列使用awk。有什么不对这个awk命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要两列添加到具有〜万列的文件。我要插入作为第一列上的每一行的NR 22。然后我想原来的第一列第二列,那么作为第三列我想插入线NR(NR),在那之后我想打印的原始列的其余部分。我想我能做到这一点具有以下AWK行:

I want to add two columns to a file with ~10,000 columns. I want to insert as the first column the nr 22 on each row. Then I want the original first column as the second column, then as the third column I want to insert the line nr (NR), and after that I want the rest of the original columns to be printed. I thought I could do that with the following awk line:

awk '{print 22, $1, NR; for(i=2;i<=NF;++i) print $i}' file

它输出的前三列(22,$ 1,NR),但是在那之后,有一个新的开始行每个值,因此该文件被打印这样的:

It prints the first three columns (22, $1, NR) well, but after that, there is a new line started for each value, so the file is printed like this:

22 $1 NR
$2
$3
$4
etc...

而不是:

22 $1 NR $2 $3 $4 etc...

我做了什么错了?

What did I do wrong?

推荐答案

如何使用的printf ,因为不是打印增加了一个新行。

How about using printf instead since print adds a newline.

awk '{printf("%d, %d, %d, ", 22, $1, NR); for(i=2;i<=NF;++i) printf("%d, ", i)}' file

或者你也可以用 ORS玩 OFS 输出记录分隔符的而输出字段分隔符的。通常你添加这些在 BEGIN 这样的语句:

Or you can play with the ORS and OFS, the Output Record Separator and the Output Field Separator. Normally you add those in a BEGIN statement like this:

awk 'BEGIN { ORS = " " } {print 22, $1, NR; for(i=2;i<=NF;++i) print $i}{print "\n"}' file 

请注意,一个额外的的printf\\ n是必要的,否则一切都在同一行结束了...

Note that an extra printf "\n" is needed, else everything ends up on one line...

阅读更多 GAWK手动输出分离

这篇关于添加列使用awk。有什么不对这个awk命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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