简体   繁体   English

在grep中使用shell变量

[英]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: 我在一个文本文件中有一个令牌列表,想要使用grep从包含这些令牌的第二个文本文件中获取行,但是似乎在用grep访问shell变量时遇到了麻烦:

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. 我已经尝试过$ n,“ $ n”,$ {n},“ $ {n}”,^ $ {n}和“ ^ $ {n}”,但它们似乎都不起作用。

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标志:

grep -f pos/1.txt dictionary.txt

This will print the lines of dictionary.txt that match the patterns in pos/1.txt . 这将打印与pos/1.txt中的模式匹配的dictionary.txt行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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