Home > Back-end >  Inserting a New Column into a CSV File
Inserting a New Column into a CSV File

Time:08-10

I need to insert a new column in front of the first column in a CSV file. I'm trying to use an awk solution

CSV File

A,B,C,D,E,F
1,2,3,4,5,6
2,3,4,5,6,7
3,4,5,6,7,8
4,5,6,7,8,9

Attempted Code

awk 'BEGIN{FS=OFS=","}{$1=$1 OFS (FNR<1 ? $1 "0\n0\n0\n0" : "col")}1'

Expected Result

col,A,B,C,D,E,F
0,1,2,3,4,5,6
0,2,3,4,5,6,7
0,3,4,5,6,7,8
0,4,5,6,7,8,9    

CodePudding user response:

One way could be to print col, if it's the first line and 0, if it's any of the other lines. Then print the rest of the columns:

awk 'NR==1 { printf("col,") } NR>1 { printf("0,") } { print }'

Broken down:

NR==1 {             # execute this block if it's the first line
    printf("col,")
}
NR>1 {              # execute this block if it's any other line
    printf("0,")
}
{                   # always execute this block
    print
}

CodePudding user response:

I would harness GNU AWK for this task following way, let file.csv content be

A,B,C,D,E,F
1,2,3,4,5,6
2,3,4,5,6,7
3,4,5,6,7,8
4,5,6,7,8,9

then

awk 'BEGIN{FS=OFS=","}{print NR==1?"col":"0", $0}' file.csv

gives output

col,A,B,C,D,E,F
0,1,2,3,4,5,6
0,2,3,4,5,6,7
0,3,4,5,6,7,8
0,4,5,6,7,8,9

Explanation: I inform GNU AWK that both field separator and output field separator is comma. For each line I print col if it is first row else 0 followed by whole line ($0).

(tested in gawk 4.2.1)

  • Related