首页 > 解决方案 > shell脚本将文件与多行模式进行比较

问题描述

我有一个在一些手动配置后创建的文件。我需要使用 shell 脚本自动检查此文件。该文件如下所示:

eth0;eth0;1c:98:ec:2a:1a:4c
eth1;eth1;1c:98:ec:2a:1a:4d
eth2;eth2;1c:98:ec:2a:1a:4e
eth3;eth3;1c:98:ec:2a:1a:4f
eth4;eth4;48:df:37:58:da:44
eth5;eth5;48:df:37:58:da:45
eth6;eth6;48:df:37:58:da:46
eth7;eth7;48:df:37:58:da:47

我想将它与这样的模式进行比较:

eth0;eth0;*
eth1;eth1;*
eth2;eth2;*
eth3;eth3;*
eth4;eth4;*
eth5;eth5;*
eth6;eth6;*
eth7;eth7;*

如果我只需要检查这个模式,我可以运行这个循环:

c=0
while [ $c -le 7 ]
do
    if [ "$(grep "eth"${c}";eth"${c}";*" current_mapping)" ]; 
    then
        echo "eth$c ok" 

fi 
    (( c++ ))
done

可能有 6 种或更多不同的模式。例如,模式也可能如下所示(取决于和特定的配置请求):

eth4;eth0;*
eth5;eth1;*
eth6;eth2;*
eth7;eth3;*
eth0;eth4;*
eth1;eth5;*
eth2;eth6;*
eth3;eth7;*

所以我认为我不能在循环中运行标准的 grep per line 命令。eth 数字并不始终相同。

是否有可能以某种方式将整个文件与模式进行比较,就像使用 grep 进行单行一样?

标签: bashshell

解决方案


假设file是您的数据文件,并且patt是包含上述模式的文件。您可以将其与替换为和的过程替换grep -f结合使用,以使其成为一个可行的正则表达式。sed*.*?.

grep -f <(sed 's/\*/.*/g; s/?/./g' patt) file

eth0;eth0;1c:98:ec:2a:1a:4c
eth1;eth1;1c:98:ec:2a:1a:4d
eth2;eth2;1c:98:ec:2a:1a:4e
eth3;eth3;1c:98:ec:2a:1a:4f
eth4;eth4;48:df:37:58:da:44
eth5;eth5;48:df:37:58:da:45
eth6;eth6;48:df:37:58:da:46
eth7;eth7;48:df:37:58:da:47

推荐阅读