Karthik
Karthik

Reputation: 83

Finding list of strings from a list that are present in a file

I am trying to grep a list of strings inside a file and trying to get the list of strings that are present in the file. Is there a way to get that?

If a, b are in file.txt

Eg: grep 'a\|b\|c' file.txt
output : a
         b

Upvotes: 0

Views: 53

Answers (1)

glenn jackman
glenn jackman

Reputation: 247250

list_of_strings=( a b "hello world" )
grep -oF -f <(printf "%s\n" "${list_of_strings[@]}") file.txt

That uses a process substitution to treat the printed array of strings like a file, then use some grep options (check your man page) to extract the desired strings

Also, using regex alternation like you seem to want:

grep -oE "$(IFS='|'; echo "${list_of_strings[*]}")" file

Upvotes: 2

Related Questions