Suppose I have a CSV file with headers of the following form:
Field1,Field2
3,262000
4,449000
5,650000
6,853000
7,1061000
8,1263000
9,1473000
10,1683000
11,1893000
I would like to write an awk script which will take a comma-separated list of field names target
, split it into an array, and then only pick out those columns with the names I specify.
This is what I have tried so far, and I have verified that the head
array contains the desired headers, and the targets
array contains the desired targets passed in by the given command line.
BEGIN{
FS=","
split(target, targets, ",")
}
NR==1 {
for (i = 1; i <= NF; i++) head[i] = $i
}
NR !=1{
for (i = 1; i <= NF; i++) {
if (head[i] in targets){
print $i
}
}
}
When I invoke this script with the command
awk -v target=Field1 -f GetCol.awk Debug.csv
I get nothing printed out.