Dave Dave - 1 year ago 62
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.

Answer Source

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

awk -F '"?,"?' '{print $2, $(NF-1)}' file.csv
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download