I am working on this awk tutorial here .
$ head file
Name,Number,Letter
Unix,10,A
Linux,30,B
Solaris,40,C
Fedora,20,D
Ubuntu,50,E
this command inserts a new column after the last column. But i do not want to add to the header, how do I do this? I will also, after this, want to add a header name after.
$ awk -F, '{$(NF+1)=++i;}1' OFS=, file
Name,Number,Letter,1
Unix,10,A ,2
Linux,30,B ,3
Solaris,40,C ,4
Fedora,20,D ,5
Ubuntu,50,E,6
You can skip the first line with:
awk -F, 'NR>1{$(NF+1)=++i;}1' OFS=, file
If there can be blanks in the file, then you can use regular expression to mask them out:
awk -F, '!/^$/ && NR>1{$(NF+1)=++i;}1' OFS=, file
To add a new header, you can do:
awk 'NR==1{$0=$0",New_header";} NR>1{$(NF+1)=++i;}1' OFS=, file
Like @jaypal said, it could be simply:
awk -F, 'NR==1{$0=$0",New_header";} NF && NR>1{$(NF+1)=++i;}1' OFS=, file
$ awk 'BEGIN{FS=OFS=","} {print $0, (NR>1?NR-1:"new header")}' file
Name,Number,Letter,new header
Unix,10,A,1
Linux,30,B,2
Solaris,40,C,3
Fedora,20,D,4
Ubuntu,50,E,5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.