R3dDr4g0n
R3dDr4g0n

Reputation: 1

How to only use an exact string as a parameter with sed

I'm trying to get a simple script to read a file named "test1.txt" and check for a string such as foo and replace just that exact string.

test1.txt is as follows:

foo = false
barfoo = false
foofoo = false

My code is as follows:

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'

What it does is that it searches the file for the first parameter and replaces the entire line with the second parameter. However, this leads to an error where if it finds a string within a larger string, it will replace the entire line.

The output is:

foo = true
foo = true
foo = true

I would like it to be:

foo = true
barfoo = false
foofoo = false

I'm still new to bash scripting and I looked for an answer for a while. So my apologies if this is a repeat question.

Upvotes: 0

Views: 47

Answers (2)

Bach Lien
Bach Lien

Reputation: 1060

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

Upvotes: 0

karakfa
karakfa

Reputation: 67507

with word boundary

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

UPDATE

For the new version of the problem, awk is a better alternative.

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

this idiom is to replace values of given key with an exact match. Assumes there are spaces surrounding equal sign.

Upvotes: 2

Related Questions