I want to use grep with two variables in a shell script
var = match
cat list.txt | while read word_from_list; do
grep "$word_from_list" "$var" >> words_found.txt
done
But grep expects to get a file as second input:
grep: match: No such file or directory
How can this be solved?
Grep works well with standard input. This allows us to use grep to match a pattern from a variable. It's is not the most graceful solution, but it works.
You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.
To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.
Grep Multiple Patterns To search for multiple patterns, use the OR (alternation) operator. The alternation operator | (pipe) allows you to specify different possible matches that can be literal strings or expression sets. This operator has the lowest precedence of all regular expression operators.
A quick scan of the grep man page suggests that you can use -e
for multiple patterns, eg.
grep -e "$word_from_list" -e "$var"
If you find yourself with a large number of patterns, you might want to use the -f
option to read these from a file instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With