简体   繁体   中英

Using a shell variable with grep

I have a list of tokens in a text file and want to use grep to get the lines from a second text file that contain those tokens, but seem to be having trouble accessing the shell variable with grep:

for n in `cat ./pos/1.txt`
do
cat dictionary.txt | grep "$n"
done

I've tried $n, "$n", ${n}, "${n}", ^${n}, and "^${n}" None of them seem to work.

Thanks

Looks like the following is what you are looking for:

for n in `cat 1.txt`
do
grep $n dictionary.txt
done

Instead of looping over the lines, it would be better to use the -f flag of grep :

grep -f pos/1.txt dictionary.txt

This will print the lines of dictionary.txt that match the patterns in pos/1.txt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM