Home > Software design >  CSV Column Insertion via awk
CSV Column Insertion via awk

Time:08-09

I am trying to insert a column in front of the first column in a comma separated value file (CSV). At first blush, awk seems to be the way to go but, I'm struggling with how to move down the new column.

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\nA\n2\nC" : "col")}1'

Result

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

Expected Result

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

CodePudding user response:

This can be easily done using paste printf:

paste -d, <(printf "col\n0\nA\n2\nC\n") file

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

<(...) is process substitution available in bash. For other shells use a pipeline like this:

printf "col\n0\nA\n2\nC\n" | paste -d, - file

CodePudding user response:

With awk only you could try following solution, written and tested with shown samples.

awk -v value="$(echo -e "col\n0\nA\n2\nC")" '
BEGIN{
  FS=OFS=","
  num=split(value,arr,ORS)
  for(i=1;i<=num;i  ){
    newVal[i]=arr[i]
  }
}
{
  $1=arr[FNR] OFS $1
}
1
'  Input_file

Explanation:

  • First of all creating awk variable named value whose value is echo(shell command)'s output. NOTE: using -e option with echo will make sure that \n aren't getting treated as literal characters.
  • Then in BEGIN section of awk program, setting FS and OFS as , here for all line of Input_file.
  • Using split function on value variable into array named arr with delimiter of ORS(new line).
  • Then traversing through for loop till value of num(total values posted by echo command).
  • Then creating array named newVal with index of i(1,2,3 and so on) and its value is array arr value.
  • In main awk program, setting first field's value to array arr value and $1 and printing the line then.
  • Related