How do I grep multiple patterns in a variable which contains multiple strings?

words=(hello world foo bar)
grep -e ${words}  text.txt

Also, I will be using words as a variable where all user inputs will be saved. Is there any way I can change the format of the variable so it can be used to grep all the strings inside?

The problem is that when I try the code above, I get all the results from text.txt regardless of them meeting the grep command.

  • 1
    What kind of result are you looking for? Lines on which all words are found or lines on which any of the words is found? Also, what operating system are you using (that tells us what flavor of grep you have)?
    – terdon
    Commented May 11, 2021 at 10:58
  • Does this answer your question unix.stackexchange.com/q/648218/72456 Commented May 11, 2021 at 11:13
  • I'm looking for all files which contain any of the given word sort of like an or operator. i'm using ubuntu in WSL
    – User10
    Commented May 11, 2021 at 13:07

1 Answer 1

words=(hello world foo bar)
grep -F -f <(printf "%s\n" "${words[@]}") text.txt

This uses process substitution to provide a "file" containing each word on its own line. The -f option tells grep to read its list of patterns to match from a file.

The -F option tells grep that the patterns are fixed strings, not regular expressions. This speeds up the pattern matching. If the words do happen to be regexes, remove this option.

You must log in to answer this question.

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