Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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
share|improve this question

2 Answers 2

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
share|improve this answer

The problem is that shell variables (including arrays) are not available inside awk. You need to pass them explicitly via -v option. Moreover you cannot pass the whole array, but you can put array into single variable and split it inside awk:

awk -va="$(echo "${array[@]}")" 'BEGIN{OFS=FS=","; split(a,b," ")}{print $0,b[NR]}' input.csv

This will work as long as you don't have spaces inside array elements.

share|improve this answer
    
actually you can stackoverflow.com/a/15787182/2002471 –  chicks Aug 28 at 4:50
    
Thanks very much. –  Rauf Aug 31 at 12:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.