Replace only if string exists in current line

Solution

Assuming your input file $target contains the following:

some text mystring some other text
some text mystring a searchstring
just some more text

This command:

sed -i -e '/searchstring/ s/mystring/1/ ; /searchstring/! s/mystring/0/' $target

will change its content to:

some text 0 some other text
some text 1 a searchstring
just some more text

Explanation

The script contains two substitute (s) commands separated by a semicolon.

The substitute command accepts an optional address range that select which lines the substitution should take place.

In this case regexp address was used to select lines containing the searchstring for the first command; and the lines that do not contain the searchstring (note the exclamation mark after the regexp negating the match) for the second one.

Edit

This command will perform better and produce just the same result:

sed -i -e '/searchstring/ s/mystring/1/ ; s/mystring/0/' $target

The point is that commands are executed sequentially and thus if there is still a mystring substring in the current line after the first command finished then there is no searchstring in it for sure.

Kudos to user946850.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)