I have a csv file with a header (first line) that looks like this
"Gene1","Gene2"
"G1","G2"
"G2","G8"
I want to add a column to this file containing number 9 so the file looks like this. I need the column name of the new column to be "Score" and the value throughout is 9
"Gene1","Gene2","Score"
"G1","G2",9
"G2","G8",9
I tried this code with awk but it is naming column 9, I want its name to be "Score" how do I do this?
awk -F ',' -v OFS=',' '{ $(NF 1) = 9; print }' infile.csv > outfile.csv
How can I do this in shell? Thank you!
CodePudding user response:
Adding a ternary operation to OP's current code to conditionally determine the new field value based on the current record number (NR
):
awk -F ',' -v OFS=',' '{ $(NF 1) = (NR==1 ? "\"Score\"" : 9); print }' infile.csv
This generates:
"Gene1","Gene2","Score"
"G1","G2",9
"G2","G8",9
CodePudding user response:
Another shorthand awk
solution:
awk '{print $0 "," (NR==1 ? "\"Score\"" : 9)}' file
"Gene1","Gene2","Score"
"G1","G2",9
"G2","G8",9
Or a sed
solution:
sed '1s/$/,"Score"/;1!s/$/,9/' file
"Gene1","Gene2","Score"
"G1","G2",9
"G2","G8",9
CodePudding user response:
With your shown samples and attempts, please try following awk
code. We need to put a separate condition for 1st line to handle headers in it then rest of the lines can be added addiotnal field in current line which is 9
in value then simply print the line.
awk 'BEGIN{FS=OFS=","} FNR==1{print $0,"\"Score\"";next} {$(NF 1)="9"} 1' Input_file
CodePudding user response:
$ awk -F, -v OFS=, 'NR==1 ? $ NF="\"Score\"" : $ NF=9' file
"Gene1","Gene2","Score"
"G1","G2",9
"G2","G8",9