梳理awk命令+添加列值和列名

时间:2015-08-12 21:58:09

标签: csv awk

我想在此csv文件中添加第5列

$ head countries_int_code.csv
country,latitude,longitude,name
AD,42.546245,1.601554,Andorra
AE,23.424076,53.847818,United Arab Emirates
AF,33.93911,67.709953,Afghanistan
AG,17.060816,-61.796428,Antigua and Barbuda
AI,18.220554,-63.068615,Anguilla
AL,41.153332,20.168331,Albania
AM,40.069099,45.038189,Armenia
AN,12.226079,-69.060087,Netherlands Antilles
AO,-11.202692,17.873887,Angola

这会将值添加到列

$ awk -F, 'NR>1 {$5="Unknown"}1' OFS=, countries_int_code.csv > countries_int_code2.csv

$ head countries_int_code2.csv
country,latitude,longitude,name
AD,42.546245,1.601554,Andorra,Unknown
AE,23.424076,53.847818,United Arab Emirates,Unknown
AF,33.93911,67.709953,Afghanistan,Unknown
AG,17.060816,-61.796428,Antigua and Barbuda,Unknown
AI,18.220554,-63.068615,Anguilla,Unknown
AL,41.153332,20.168331,Albania,Unknown
AM,40.069099,45.038189,Armenia,Unknown
AN,12.226079,-69.060087,Netherlands Antilles,Unknown
AO,-11.202692,17.873887,Angola,Unknown

这为列提供了名称

$ awk -F, 'NR<=1 {$5="ColName"}1' OFS=, countries_int_code2.csv > countries_int_code3.csv


$ head countries_int_code3.csv
country,latitude,longitude,name,ColName
AD,42.546245,1.601554,Andorra,Unknown
AE,23.424076,53.847818,United Arab Emirates,Unknown
AF,33.93911,67.709953,Afghanistan,Unknown
AG,17.060816,-61.796428,Antigua and Barbuda,Unknown
AI,18.220554,-63.068615,Anguilla,Unknown
AL,41.153332,20.168331,Albania,Unknown
AM,40.069099,45.038189,Armenia,Unknown
AN,12.226079,-69.060087,Netherlands Antilles,Unknown
AO,-11.202692,17.873887,Angola,Unknown

我可以只使用tmpfile写入,然后将其重命名为原始文件,而不是写入各种文件。 ... countries_int_code.csv > tmpfile && mv tmpfile countries_int_code.csv

但是我可以将上面的2个awk命令组合到1个命令中来完成所有操作,所以我可以在1个命令中添加列值和列名吗?

1 个答案:

答案 0 :(得分:1)

$ awk 'BEGIN{FS=OFS=","} {print $0, (NR>1?"Unknown":"ColName")}' file
country,latitude,longitude,name,ColName
AD,42.546245,1.601554,Andorra,Unknown
AE,23.424076,53.847818,United Arab Emirates,Unknown
AF,33.93911,67.709953,Afghanistan,Unknown
AG,17.060816,-61.796428,Antigua and Barbuda,Unknown
AI,18.220554,-63.068615,Anguilla,Unknown
AL,41.153332,20.168331,Albania,Unknown
AM,40.069099,45.038189,Armenia,Unknown
AN,12.226079,-69.060087,Netherlands Antilles,Unknown
AO,-11.202692,17.873887,Angola,Unknown