【发布时间】:2022-10-13 23:23:21
【问题描述】:
我正在尝试执行以下操作:
我有一个名为 testing.txt 的文件,我想在每次 IP 地址或地址根据名称(test1ip、test2ip)更改时更新它:
127.0.0.1 localhost
somotherrandomip testing
192.168.0.36 test1ip
192.168.0.37 test2ip
这是我尝试过的。
#!/bin/bash
array=(
"192.168.0.34 test1ip"
"192.168.0.35 test2ip"
)
for i in "${array[@]}"; do
if ! grep -Fxq "$i" testing.txt
then
echo "ip-name=$i is not present, so adding it in testing.txt file"
echo "$i" >> testing.txt
else
echo "ip-name=$i is present in file, so nothing to do"
fi
done
但是,如果未找到该行,则此脚本会附加一个全新的行。我想要实现的是如果找到 test1ip 或 test2ip 但 IP 地址发生变化,则覆盖该行。
预期结果:
127.0.0.1 localhost
somotherrandomip testing
192.168.0.34 test1ip
192.168.0.35 test2ip
我也读过这个How to check if a string contains a substring in Bash,但似乎我无法弄清楚。
任何帮助是极大的赞赏!
【问题讨论】:
标签: bash