如果子字符串在 bash 中匹配,则替换整个字符串

如果子字符串在 bash 中匹配,则替换整个字符串

如果子字符串与字符串的一部分匹配,我试图替换字符串,但无法实现它。从子字符串匹配整个字符串的正则表达式是什么。这是我的代码和我尝试应用它的文件。

#!/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

答案1

$ 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

这会将您的文件视为一组  = -delimited 行。当第一个字段匹配时Server,它将被替换为字符串puppetserver。然后输出这些行。

从 shell 变量中获取字符串Server和:puppetserver

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 =

相关内容