0

I have a CSV file as below

input.csv
1,2,3
4,5,6,7,8
9,10,11,12

From this I want to get

output.csv
3
8
12

I know for a particular fixed size column then I can use

cut -d \, -f 1 >output.csv

Since this column position varies I could not find it out.Any help is appreciated.Thanks in advance.

1
  • Be careful trying to just split on , if your CSV could contain , within a field, as is often the case. At that point you really need to parse each line, not just tokenize it Oct 21 '16 at 11:39
5

A solution is:

awk -F "," '{print $NF}' input.csv > output.csv
3

awk -F, '{print $NF}' is best suited in this case as given already


Other ways:

You can reverse the lines, get first column and then reverse again

$ rev input.csv | cut -d, -f1 | rev
3
8
12


Using sed

$ sed 's/.*,\(.*\)/\1/' input.csv 
3
8
12


Using grep and pcre

$ grep -oP '.*,\K.*' input.csv  
3
8
12
0

I'd recommend using something that can actually parse CSV files, in case the last field contains commas itself, like, say

13,14,15,"this, here"

The last field there is this, here, not here"

I'd use python, which you could put into a script or you could fake the script at the command line like

python <(cat <<EOSCRIPT
import sys
import csv
f = csv.reader(open(sys.argv[1]))
for row in f:
  print row[-1]
EOSCRIPT
) input.csv > output.csv 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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