-4

How do I search two strings in two different columns in a .csv file and print output only if both strings are in same row.

Both string values are stored in two variables.

First string to be searched in 2nd column and second string to be searched in 4th column of a .csv file and print output only if both string match found in same row.

I tried with below command to search for one matched string in a row, but how can I do matching about two strings in two different columns?

awk -v pat="$list" -F":" '$0 ~ pat { print $1, $2, $3, $4 }' filename.csv
1

Using awk:

awk -v pat1="$var1" -v pat2="$var2" -F, '($2==pat1&&$4==pat2)' infile.txt 
0

Using GNU sed you can accomplish your task as given:

# bash function to properly escape the variable contents
# s.t. it can be used on the LHS of a sed s/// command
escVar() {
   printf '%s\n' "$1" | sed -e 's:[][^\./$*]:\\&:g'
}

# now define your patterns to be used
pat1=$(escVar "$DC")
pat2=$(escVar "$CountryCpde")

# main...
sed -Ee '
   h;s/[^,]+/\n&\n/2; s/[^,]+/\n&\n/4'"
   /\n.*$pat1.*\n.*\n.*$pat2.*\n/"'!d;g
' filename.csv

Also, you may use Perl for this task:

perl -F, -slane '
   BEGIN{ @h{qw/1 3/} = (*pat1, *pat2); }
   print if 2 == grep { 1 + index $F[$_], ${$h{$_}} } qw/1 3/;
' -- -pat1="$DC" -pat2="$CountryCode" -- filename.csv

Working

  • Set the field separator to a comma, and turn on the auto-read-in of file (-n), -s will enable variables to be declared on the command line.
  • Set up a hash whose values are typeglobs *pat1, *pat2.
  • Then look for pat1 in 2nd field $F[1] and pat2 in 4th field $F[3] and only when are both found on the same record should that record be printed.
  • Tried the shell command but getting error escVar: command not found Heloo.sh: line 7: escVar: command not found sed: invalid option -- 'E' Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]... -n, --quiet, --silent – user245596 Aug 9 '17 at 18:20

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.