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

これはファイルを区切りの行セットとして扱います  = 。最初のフィールドが一致すると、Server文字列に置き換えられますpuppetserver。次に、次の行を出力します。

シェル変数から文字列の合計を取得しますServerpuppetserver

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これは、文字ではなく文字で囲まれた文字列と=最大1=文字を一致させて置き換えますpuppetserver =

おすすめ記事