Consider below two variables


Have a CSV file, fileSB.csv. I found a command (below) to search for the DC variable name in 2nd column and CountryCode variable name in 4th column. Only if both variable matches in the same line, then that particular line will be printed.

Now my requirement is that in the same row/line as detected using below command, I want to print only the values present in 12th column. The problem here is that 12th column can have any number of commas in it and hence not able to print values in 12th column

Command to print line that matches both variable values from file name fileSB.csv is

awk -v pat1="$DC" -v pat2="$CountryCode" -F, '($2==pat1&&$4==pat2)' fileSB.csv

Summary: Need to get the 12th column from the comma-separated output of awk, which may contain any number of commas, and is followed by another 10 columns.

  • 2
    -1 for not putting requested information into the question (and for calling it a CSV file when it isn’t). – G-Man Says 'Reinstate Monica' Oct 3 '17 at 20:51

According to comments below, the 12th column contains a variable number of comma-separated items, followed by 10 more columns.

awk -v pat1="$DC" -v pat2="$CountryCode" -F, '$2 == pat1 && $4 == pat2' fileSB.csv |
cut -d, -f 12- | rev | cut -d, -f 11- | rev

The cut and rev calls will first remove the 11 first columns, and then reverse the data and remove the last 10 column (now the first 10 columns after the reversal), and then reverse it again.

| improve this answer | |
  • tried above command but it shows unbound variable – user8554534 Oct 3 '17 at 18:25
  • @user8554534 If I had any data to test on, I could try to reproduce what you're seeing. Do update you question with a bit of data that I and others could use to help you. – Kusalananda Oct 3 '17 at 18:27
  • consider a excel file that many number of lines in it. Using command awk -v pat1="$DC" -v pat2="$CountryCode" -F, '$2 == pat1 && $4 == pat2' fileSB.csv, output is 1,7777777,hi, IN, one,two,three,four,five,six,red,114.14,15.21, 16 rr,ten,eleven where in the line value from 114.14,15.21, 16 rr represents 12th column value and the value inside the column can vary – user8554534 Oct 3 '17 at 18:31
  • 3
    @user8554534 That's not a valid CSV formatted dataset. Column 12 should be quoted... Is column 12 the last column? – Kusalananda Oct 3 '17 at 18:41
  • 2
    @user8554534 Additional information should go in the question, not in comments. This is particularly true of important information like example usage. – Faheem Mitha Oct 3 '17 at 20:23

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