如何使用其他文件中的搜索参数grep文件

Eri*_*ric 10 bash grep for-loop

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

for i in $(cat ip.file); do grep $i fw.config; done
Run Code Online (Sandbox Code Playgroud)

但这样做绝对没有任何回报.如果我将上面的脚本放入一个文件并使用bash -xv标志执行它,每行返回如下内容:

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

grep 1.2.3.4 fw.config正是我想要发生的事情,但我从这个命令得不到任何回报.

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

Joh*_*ica 22

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

顺便说一句,您可以使用grep -f FILE传递grep模式列表进行搜索.然后它将执行单次搜索以查找任何这些模式.

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

# Or...
grep -f <(dos2unix < ip.file) fw.config
Run Code Online (Sandbox Code Playgroud)


gho*_*g74 5

GNU grep,

grep -f ip.txt config
Run Code Online (Sandbox Code Playgroud)

它也建议不要用于与猫循环.(如果这样做,您应该将IFS更改为$'\n').改为在读取循环时使用.

while read -r line
do
  ....
done <"ip.txt"
Run Code Online (Sandbox Code Playgroud)