如何仅使用精确字符串作为sed的参数

时间:2018-01-23 23:55:34

标签: string shell sed

我试图让一个简单的脚本来读取名为" test1.txt"的文件。并检查一个字符串,如foo,并替换该确切的字符串。

test1.txt如下:

foo = false
barfoo = false
foofoo = false

我的代码如下:

ChangeSettings(){
if [[ $(grep $1 test1.txt) ]]; then
    sudo sed -i "/$1/c $2" test1.txt
else
    sudo echo >> test1.txt "$2"
fi
}
ChangeSettings foo 'foo = true'

它的作用是在文件中搜索第一个参数,并用第二个参数替换整行。但是,这会导致错误,如果它在较大的字符串中找到一个字符串,它将替换整行。

输出结果为:

foo = true
foo = true
foo = true

我希望它是:

foo = true
barfoo = false
foofoo = false

我还是新手来编写脚本,我找了一段时间的答案。如果这是一个重复的问题,我很抱歉。

2 个答案:

答案 0 :(得分:2)

带有字边界

sed 's/\bfoo\b/& = true/' file

<强>更新

对于问题的新版本,awk是更好的选择。

awk 'BEGIN{FS=OFS=" = "} $1=="foo"{$2="true"}1' file 

这个习惯用于用完全匹配替换给定键的值。假设有等号的空格。

答案 1 :(得分:0)

from='foo';to='foo = true';sed "/^ *$from *=/{s:^.*\$:$to:}"
                                       ^            ^
                                       |____________|___ line begins with "$from"
                                                    |___ replace line with "$to"