簡體   English   中英

使用 AWK 或 SED 替換 IP

[英]Replace IP using AWK or SED

我必須在腳本中替換 IP,所以我使用變量來存儲 awk 的 output,例如:

existing_ip=$(awk --field-separator '=' '/10.171.0.231/ { print $2; }' file.txt)

另一方面,我也接受用戶輸入,例如:

read -p  "What is the IP address to be replace: " new_ip

echo -e "New IP: ${new_ip}"

現在在下一步中,當我嘗試用 sed 或 awk 命令替換 IP 時,我遇到了一個問題。 我曾嘗試使用以下命令,但均未奏效。

awk -v s="$existing_ip"  '{gsub(/10.171.[0-9].{1,3}.[0-9]/, s)}1'

sed -i "s/${existing_ip}/${new_ip}/g"

幫助將不勝感激。

除了在評論中提到您必須指定輸入文件之外,模式10.171.[0-9].{1,3}.[0-9]可以匹配例如10a171b0cdef2因為您必須轉義點才能匹配從字面上看。

如果你轉義點,量詞{1,3}將 go 在匹配末尾的數字后。 所以你會在第 3 部分匹配一個數字,在第 4 部分匹配 1-3 個數字。

cat file.txt

This is ip 10.171.1.111 and this is ip 10.172.0.231

例如

existing_ip="10.171.0.231"
awk -v s="$existing_ip"  '{gsub(/10\.171\.[0-9]\.[0-9]{1,3}/, s)}1' file.txt

Output

This is ip 10.171.0.231 and this is ip 10.172.0.231

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM