Dave Dave - 7 months ago 24
Bash Question

How do I write a shell command to extract the second and second to last columns of a CSV file?

I'm using bash shell on Mac Yosemite. I found this command for extracting the second column of a CSV file ...

awk -F "\"*,\"*" '{print $2}'

but my quesiton is what if I want to extract both the second and second-to-last column? For simplicity, we can assume there is more than one column in the CSV data.


You can use $(NF-1) to get second-to-last column:

awk -F '"?,"?' '{print $2, $(NF-1)}' file.csv