awk: add new column, including header

拥有回忆 提交于 2021-02-08 09:45:07

问题


I have a file that looks like this:

name measurement gender duration
a 1 m 55
b 1 f 54
c 2 m 53
... etc

I want to use awk to add a column, which has the same value for every row, except the first (the header). Let's say I want to add the column new_column with the value 99 for every row, so the output file looks like this:

name measurement gender duration new_column
a 1 m 55 99
b 1 f 54 99
c 2 m 53 99
... etc

This sounds like a job for awk... but I haven't been able to figure out how. Any ideas? Many thanks!


回答1:


$ awk '{s=(NR==1)?"new_column":"99";$0=$0 OFS s}1' file
name measurement gender duration new_column
a 1 m 55 99
b 1 f 54 99
c 2 m 53 99



回答2:


You can use this awkcomand:

awk 'NR==1{$(NF+1)="new column"} NR>1{$(NF+1)="99"}1' file



回答3:


You could golf it like this (assuming you have no empty lines):

awk '$++NF=NR==1?"new_column":99' infile

Output:

name measurement gender duration new_column
a 1 m 55 99
b 1 f 54 99
c 2 m 53 99


来源:https://stackoverflow.com/questions/47220452/awk-add-new-column-including-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!