Adding column in CSV file using awk

awkcommand linetext processing

I need to a add a column in CSV file from an array using awk.

For example,

input.csv

a,10
b,11

array = (100 200)

output.csv should look like

a,10,100
b,11,200

I tried this command but it does not work

awk -F"," 'BEGIN { OFS = "," } {for (x in array) $3=array[x]; print}' input.csv> output.csv

Best Answer

Do you have to use awk for this? The paste utility was designed exactly for this sort of thing. Assuming array is a shell array:

array=(100 200)
printf "%s\n" "${array[@]}" | paste -d, input.csv - > output.csv

The printf is simply to put each array member on a new line. paste then pastes together input lines from input.csv and - (i.e. the piped output from printf), using a comma as a delimiter.


If your array happens to be a newline separated file, e.g. array.txt:

100
200

then it is even easier:

paste -d, input.csv array.txt > output.csv
Related Question