I have a line such as:
sed -i 's/mystring/newstring/' $target
This command will change all mystring
to newstring
.
What I want now is: when the program sees mystring
, how can I check for the current line if the string searchstring
exists or not? If it exists, newstring
is 1
; otherwise, newstring
is 0
.
Solution
Assuming your input file $target contains the following:
This command:
will change its content to:
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:
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.
This is from the sed one-liners page:
Speed is not the issue of the question at hand, but the syntax hints help formulating the solution: