问题
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