I have a script that finds a string in a file replaces it with a new string.
$ sed -i 's/$old_string'/'$new_string'/g' $FILENAME
Now I need the condition to be a regular expression that also check whether the old string is followed with anything but a number.
I tried this but it didn't work:
$ sed -i -r 's/$old_string(^[0-9])+/$new_string/g' $FILENAME
Any idea?
To negate a range in a regular expression, the caret must be inside the square brackets.
The parentheses are also unnecessary in this case if you are not using backreferences (and it doesn't look like you are.)
One last thing: bash doesn't parse variables inside single-quotes, so
$old_string
and$new_string
will not be replaced by any bash variable you may have set in your script but will be used literally in thatsed
command. If you use double-quotes, they will be replaced.Update:
Since the file doesn't contain anything after the string you want to replace, the
[^0-9]+
part of the regex has nothing to match. It would work if there was a space after the IP address. We can match the end of the line instead with$
.One more update. This one matches any character that isn't a number or no characters at all. For this one we need the parentheses to group the two options.
Since we have the parentheses, you can use a backreference to include whatever was matched: