私のスクリプトは次のとおりです
n="y"
while [ "{n}" = "y" ]
if [ $n == "n" ];
then
break;
fi
echo "n is $n"
do
read -p "Enter the word to find = " word
read -p "Enter word to replace = " replace
echo "$word n $replace"
#sed -i r.text.bak 's/$word/$replace/g' r.txt
sed -i "s/$word/$replace/g" "test.txt"
echo "do you have further replacement? n or y"
read temp
n=$temp
done
私の問題は、部分一致も置き換えることです。たとえば、次の行の場合:
1.1.1.14 1.1.1.14567
私は次のような結果を得ます。
1.1.1.3 1.1.1.3567
しかし、私は次のことを楽しみにしています。
1.1.1.3 1.1.1.14567
この問題をどのように解決できますか?
ベストアンサー1
完全な単語だけが一致するように正規表現を作成する必要があります。 GNUを使用すると、単語の境界で一致するものを使用sed
できます。\b
sed -i "s/\b$word\b/$replace/g"
常にスペースがあることがわかっている場合は、スペースを追加できます。
sed -i "s/ $word /$replace/g"
今スクリプトにもいくつかの問題があります。あなたのif ... break
主張は役に立たない。彼らはwhile
すでに問題に取り組んでいます。必要なものは次のとおりです。
#!/usr/bin/env bash
n="y"
while [ "$n" = "y" ]
do
echo "n is $n"
read -p "Enter the word to find = " word
read -p "Enter word to replace = " replace
echo "$word n $replace"
sed -i "s/\b$word\b/$replace/g" test.txt
echo "do you have further replacement? n or y"
read temp
n="$temp"
done