2

I would like to extract some rows from a file based on their match on a single column with a list of words.

In awk, I could use something like this:

awk '$5 == "someword" {print}' file.txt

I know that I can use grep like this:

grep -f listofwords.txt file.txt

Could you please tell how I could grep a list of words based on a single column of my file?

Example

A   something  something2
B   something2 something3
C   something3 something4
D   something4 something5
G   something5 something6

Vector of words that I want based on column 2:

something
something4

Desired output:

A   something  something2
D   something4 something5

2 Answers 2

4

This looks like a common use-case for awk to me:

awk 'NR == FNR { keywords[$1]=1; next; }
               { if ($2 in keywords) print; }' listofwords.txt file.txt

We pass two files to awk; when the condition "NR == FNR" is true (the number of records is the same as the number of records in the current file -- meaning, we're reading the first file), then save the list of keywords in the "keywords" array and skip to the next record. The other (blanket) condition checks to see if field 2 (of file.txt) is one of the key words; if so, print the line.

2
  • 1
    keywords[$1]=1 can be just keywords[$1] and { if ($2 in keywords) print; } just $2 in keywords.
    – Ed Morton
    Jul 8, 2022 at 4:29
  • 1
    That's some tricky golfing there, Ed! Thank you for the suggestions! I'm (obviously) an occasional awk user, so I tend to be a bit more verbose -- if only to help my future self understand what I was doing :)
    – Jeff Schaller
    Jul 8, 2022 at 11:52
1

You could use a while loop as each string in the list would need word boundary.

while read -r list; do
    grep -E "^[^ ]* +$list\>[^ ]* +.*$" input_file
done < list_file
A   something  something2
D   something4 something5

or

$ grep -Ee '^[^ ]* +something\>[^ ]* +.*$' -e '^[^ ]* +something4[^ ]* +.*$' input_file
A   something  something2
D   something4 something5

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .