Issue
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!
Solution
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
Answered By - markp-fuso Answer Checked By - Robin (WPSolving Admin)