bash 如何使用另一个文件中的搜索参数对文件进行 grep

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3623047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:38:25  来源:igfitidea点击:

How to grep a file using search parameters from another file

bashgrepfor-loop

提问by Eric

I am trying to use a file containing IP addresses as the basis for searching through a Cisco firewall configuration file. Normally, I would use something like:

我正在尝试使用包含 IP 地址的文件作为搜索 Cisco 防火墙配置文件的基础。通常,我会使用类似的东西:

for i in $(cat ip.file); do grep $i fw.config; done

But doing that returns absolutely nothing. If I put the above script into a file and execute it with the bash -xv flags, each line returns something like this:

但这样做绝对不会带来任何回报。如果我将上述脚本放入一个文件中并使用 bash -xv 标志执行它,每一行都会返回如下内容:

+ for i in '`cat ip.file`'
+ grep $'1.2.3.4\r' fw.config  (each IP address is different)

grep 1.2.3.4 fw.config is exactly what I want to happen, but I get nothing back from this command.

grep 1.2.3.4 fw.config 正是我想要发生的,但我从这个命令中没有得到任何回报。

I know of the grep -f option, but that also returns nothing. I am not an experienced coder, so I might be overlooking something obvious.

我知道 grep -f 选项,但这也不返回任何内容。我不是一个有经验的编码员,所以我可能会忽略一些明显的东西。

回答by John Kugelman

It looks like ip.fileis in DOS format and has \r\nline endings. Run dos2unixon it to convert to UNIX format. This will get rid of the errant \rcarriage returns that are messing up grep.

它看起来像是ip.fileDOS 格式并且有\r\n行尾。dos2unix在其上运行以转换为 UNIX 格式。这将摆脱\r混乱的错误回车grep

By the way, you can use grep -f FILEto pass grepa list of patterns to search for. It will then do a single pass searching for any of those patterns.

顺便说一下,您可以使用grep -f FILE传递grep要搜索的模式列表。然后它会单次搜索这些模式中的任何一个。

# After doing `dos2unix ip.file'...
grep -f ip.file fw.config

# Or...
grep -f <(dos2unix < ip.file) fw.config

回答by ghostdog74

GNU grep,

GNU grep,

grep -f ip.txt config

Its advisable also not to use for loop with cat. (If you do, you should change IFS to $'\n'). Use while read loop instead.

建议不要将 for 循环与 cat 一起使用。(如果这样做,您应该将 IFS 更改为 $'\n')。改用 while 读取循环。

while read -r line
do
  ....
done <"ip.txt"

回答by user304132

for i in $(tr '\r' '\n' < ip.file); do grep $i fw.config; done