我正在嘗試執行以下操作:
我有一個名為 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
我還閱讀了如何檢查字串是否包含 Bash 中的子字串,但似乎我無法弄清楚。
任何幫助是極大的贊賞!
uj5u.com熱心網友回復:
以下適用于我的機器。我將陣列更改為關聯陣列,將 -x 選項洗掉為 grep,并用于sed就地編輯檔案。
#!/bin/bash
#associative array
declare -A array=(
[test1ip]="192.168.0.34"
[test2ip]="192.168.0.35"
)
#Loop over keys of the array
#See parameter expansion in bash manpage
for i in "${!array[@]}"; do
if ! grep -Fq "$i" testing.txt
then
echo "ip-name=$i is not present, so adding it in testing.txt file"
echo "${array[$i]} $i" >> testing.txt
else
echo "ip-name=$i is present in file so running sed"
#Replace old IP vith new IP
sed -Ei "s/[0-9] (\.[0-9] ){3} $i/${array[$i]} $i/" testing.txt
fi
done
uj5u.com熱心網友回復:
這是一個bash awk解決方案,可以有效地完成這項作業:
#!/bin/bash
array=(
"192.168.0.34 test1ip"
"192.168.0.35 test2ip"
"192.168.0.33 test3ip"
)
awk '
FNR == NR {
aarr[$2] = $1
next
}
! ($2 in aarr)
END {
for (host in aarr)
print aarr[host], host
}
' <(printf '%s\n' "${array[@]}") testing.txt
127.0.0.1 localhost
somotherrandomip testing
192.168.0.33 test3ip
192.168.0.34 test1ip
192.168.0.35 test2ip
筆記:
bash的<( commands )被稱為程序替代。它創建一個檔案,其中包含commands您可以用作引數的輸出。awk'sFNR == NR是選擇第一個檔案引數的條件。在這個塊中,我創建了一個關聯陣列,它將主機名轉換為其新的 IP 地址。! ($2 in aarr)表示列印主機名不在翻譯陣列中的記錄。END用于列印翻譯陣列(主機名的新 IP)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/447737.html
