Bash

如果子字元串在 bash 中匹配,則替換整個字元串

  • August 15, 2021

如果子字元串與字元串的一部分匹配,我正在嘗試替換字元串,但無法實現。匹配子字元串中的整個字元串的正則表達式是什麼。這是我的程式碼和我試圖將其應用到的文件。

#!/bin/bash -x
STR='Server'
RSTR='puppetserver'
{ while IFS='=' read name ip
   do
       if [[ "$STR" == *${name}* ]]; then
       sed -i -e "s/*${name}*/${RSTR}/g"
       echo "Replaced with ${RSTR}."
fi
   done
} < file.txt

文件.txt

Puppet-Agent-01 = 18.208.175.32
Puppet-Agent-02 = 18.207.194.126
Puppet-Agent-03 = 3.86.54.233
Puppet-Server-01 = 54.224.89.3
$ cat file
Puppet-Agent-01 = 18.208.175.32
Puppet-Agent-02 = 18.207.194.126
Puppet-Agent-03 = 3.86.54.233
Puppet-Server-01 = 54.224.89.3
$ awk -F ' = ' 'BEGIN { OFS=FS } $1 ~ /Server/ { $1 = "puppetserver" }; 1' file
Puppet-Agent-01 = 18.208.175.32
Puppet-Agent-02 = 18.207.194.126
Puppet-Agent-03 = 3.86.54.233
puppetserver = 54.224.89.3

這會將您的文件視為一組 - =分隔的行。當第一個欄位匹配Server時,它被字元串替換puppetserver。然後輸出這些行。

獲取字元串Serverpuppetserver從 shell 變數中獲取:

awk -v patstring="$STR" -v repstring="$RSTR" -F ' = ' \
   'BEGIN { OFS=FS } $1 ~ patstring { $1 = repstring }; 1' file

或來自環境變數:

export STR RSTR
awk -F ' = ' 'BEGIN { OFS=FS } $1 ~ ENVIRON["STR"] { $1 = ENVIRON["RSTR"] }; 1' file

改為使用sed

sed 's/^[^=]*Server[^=]*=/puppetserver =/' file

這匹配字元串Server,可能被非字元包圍=,最多一個=字元,並將其替換為puppetserver =

引用自:https://unix.stackexchange.com/questions/664724