如何检查文件中存在的子字符串?

How to check sub string present in a file ?

我想用 shell 脚本在文件中编写一些规则。但在添加任何规则之前,我想检查一些条件。这是我的文件:

示例:

我写了一些规则,例如:

/home/Desktop/myfile.txt

iptables -t nat -A PREROUTING -p tcp -m tcp --dport 666 -j DNAT --to-destination 192.168.19.55
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 633 -j DNAT --to-destination 192.168.19.44
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 656 -j DNAT --to-destination 192.168.19.88

现在如果文件在添加新规则时包含相同的端口和 IP,脚本应该打印规则已经存在。如果现有文件中只有端口,脚本应该打印已在使用的端口。否则,我想打印成功。

case 1 : if i add 666 port with 192.168.19.55 IP , the script should print rule already exist .
case 2 :  if i add 666 port with 192.168.66.55 IP , the script should print port already used  .
case 3 : otherwise script print success . 

我尝试编写简单的 shell 脚本,参数为 IP 和端口:

#!/bin/shell
if [ $# -eq 2 ] 
then
    //How to check the above conditions with file /home/Desktop/myfile.txt ??
    //Need to add this rule to the myfile.txt 
    iptables -t nat -A PREROUTING -p tcp -m tcp --dport  -j DNAT --to-destination 
else
    echo "invalid arguments"
fi

您可以使用grep查看文件内容。注意.在正则表达式中比较特殊,所以我使用参数扩展将其替换为\.,字面上匹配点。

#!/bin/bash

config=/home/Desktop/myfile.txt

ip=
port=

if grep -q -- "--dport $port .*--to-destination ${ip//./\.}$" "$config"; then
    echo Rule already exists. >&2
    exit 1

elif grep -q -- "--dport $port " "$config"; then
    echo Port already used. >&2
    exit 1

else
    echo iptables -t nat -A PREROUTING -p tcp -m tcp --dport $port -j DNAT --to-destination $ip
fi

这只是一个例子。实际上,端口和目标在配置文件中的出现顺序可能不同,因此表达式会更复杂。从仅包含给定格式的所需信息(即两列,目标和端口)的文件生成文件可能更容易。

awk -v port= -v ip= '( == port &&  == ip) { print "rule already exists"  } ( == port &&  != ip) { print "Port already in use" } ( != port &&  != ip) { print "success";system("iptables -t nat -A PREROUTING -p tcp -m tcp --dport "" -j DNAT --to-destination ") }' myfile.txt

使用 awk,我们可以只集中第 11 个 space 分隔的端口数据和第 15 个 IP 地址数据,并根据传递的端口和 IP 参数检查它,打印所需的文本在特定条件下 运行 iptables 命令成功。