Get a list of column headers from a csv file and identify each with a field number

Let's say I'm processing a csv file with awk and need to quickly figure out which columns would correspond to which field numbers. Here's one way to do it:

cat input.csv 
one,two,three,four
bla,bla,blaah,blah
bla,bla,blaah,blah
bla,bla,blaah,blah
header=$(head -1 input.csv)
for f in $(seq 1 $(echo $header | awk -F',' '{print NF}'))
 do echo $f: $(echo $header | awk -F',' "{print$""$f""}")
done
1: one
2: two
3: three
4: four

I'm pretty sure there has to be a more elegant, perhaps a pure awk, way to do this, so if anyone knows one, please leave a comment. 🙂

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).