Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using grep with two variables

Tags:

grep

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?

like image 990
rt_732 Avatar asked Nov 01 '09 16:11

rt_732


People also ask

Can you use grep with a variable?

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.

How do I print multiple lines in grep?

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.

How do I grep multiple files?

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.

How do you grep 2 patterns at a time?

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.


1 Answers

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.

like image 168
Hasturkun Avatar answered Sep 29 '22 00:09

Hasturkun