Home > Enterprise >  Unix: How can I search for a word that appears in a column in a csv
Unix: How can I search for a word that appears in a column in a csv

Time:10-11

I have a csv data set with two columns that looks like this

Andrew, hello I'm from Germany
Andy,   I'm from Cambodia
Arthur, I come from Hong Kong
Alec,   I'm of african descent
Richard,I'm chinese
Tess,   I'm Tess, i also come from Cambodia

If I wanted to search the second column of this csv for the keyword 'cambodia' and return something that looks like

Andy,   I'm from Cambodia
Tess,   I'm Tess, i also come from Cambodia

I've tried $ cut -d ',' -f1,2 file | grep -i "\bcambodia\b" However this code also searches the first column, which I do not want, I only want to search the second column, and I want to keep the first column in the output

CodePudding user response:

You could consider awk using the comma as a delimiter

$ awk -F, '/Cambodia/ && $1 !~ /Cambodia/' input_file
Andy,   I'm from Cambodia
Tess,   I'm Tess, i also come from Cambodia

By using , delimiter, you can exclude column 1 matching the string $1 !~ /Cambodia/ while matching every other column that will contain the string

  • Related