Reputation: 73
I'm trying to search a string from a csv file and if a match is found then return corresponding $N columns value, otherwise return N/A. Say my csv file name is Book1.csv and the content is like,
a, this, that, those
b, something, many thing, anything
c, duck, goose
d, rock, paper, scissor
My goal is to search say c
and print corresponding column say 2nd columns value from it. In this case the output will be duck
I've tried to use this command awk -F "c\"*,\"*" '{print $2}' /home/linuxmint/Desktop/test/Book2.csv
This works however it also return non matching value as blank output. I only need matching output in this case.
Would appreciate any help on this. Thanks for reading.
Upvotes: 0
Views: 719
Reputation: 73
Although @Raman Sailopal solution works, I just wanted share few more answers which were posted by @jared_mamrot
awk_query=$(awk -F',' '/\ycom.google.android.gm\y/ {print $2}' Book2.csv) && if [ "$awk_query" ]; then awk_query="$awk_query"; else awk_query="N/A"; fi
echo $awk_query
and @tshiono
result=$(grep -wr "com.google.android.gm" Book2.csv | cut -d, -f2 | grep . || echo "N/A")
echo $result
EDIT: I've updated the solution when a user might need to match whole word. Like,
com.google.android.gm Gmail
com.google.android.gms Google Play Services
Upvotes: 2
Reputation: 12887
Try the following:
var=$(awk -F, -v col=3 -v srch="c" '{ for(i=1;i<=NF;i++) { if ($i==srch) { if ( $(col)!="") { print $(col);fnd=1 } } } } END { if (fnd!=1) { print "N/A" } }' /home/linuxmint/Desktop/test/Book2.csv)
Pass the comma separated field you want to output as a variable "col" and the string to search for as a variable "srch". Loop through each comma separated field and check if it matches srch. If it does print the field designated by col and also set a variable "fnd" to 1. At the end of processing the lines, if fnd is not 1, print "N/A" Read the result into a variable "var"
Upvotes: 2