开发者

Using grep with two variables

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:

gr开发者_运维问答ep: match: No such file or directory

How can this be solved?


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.


Two things.

  1. You need to specify the input file. Use - for standard input or supply the filename, either way it is the second parameter.
  2. After that there are a couple ways to get a boolean and via grepping. Easiest way is to change:

    grep "$word_from_list" "$var" >> words_found.txt

to:

grep "$word_from_list" - | grep "$var" >> words_found.txt

Alternatively, you can use egrep which takes in regular expressions. To get an boolean and condition you have to specify both ordering cases. The .* allows gaps between the words.

egrep "($word_from_list.*$var)|($var.*$word_from_list)" >> words_found.txt


If you have a string variable you want to search within for another string using grep, echo the string to stdout first, then use grep as you would from the command line with pipes.

var = match

cat list.txt | while read word_from_list
do
    echo "$word_from_list" | grep "$var" >> words_found.txt
done

or to take an action on a match

if [ -n "$(echo "$word_from_list" | grep "$var")" ]
then
    echo "$var" >> vars_found.txt
fi

Don't forget to carefully quote the variable you send to stdout. Forgetting the quotes will eliminate any line breaks in the string (false positives). Using single quotes will prevent the variable from being replaced with its value.


You can use egrep (extended grep), if you want to search lines containing both words on a line you could use:

egrep "($word_from_list|$var)"

If you mean lines containing $var after $word_from_list the following might be clearer:

cat list.txt | while read word_from_list; do
    egrep "$word_from_list.*$var" >> words_found.txt
done

Come to think about it, on what text do you actually want to grep? The stdin is used for the wordlist, did you miss the filename argument to grep in your example?


Here we assume number.txt as actual file and checknum.txt contain what to be search for,

we can search with the help of "for"

 # cat numbers.txt
 one ghi kjdf
 two dlfd ldlf
 three bnbbnb dddd
 four dddd
 asdf five
 # cat checknum.txt
 two
 five
 # for i in `cat checknum.txt` ; do grep $i numbers.txt ; done
 two dlfd ldlf
 asdf five

Thanks.


Try this. It probably works.

var='Match'
cat list.txt | while read word_from_list
do
    echo $word_from_list | grep -Eq $var && echo $word_from_list >> words_found.txt
done
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜