Reputation: 127
This was previously asked at the below url, but only done using the a forward-slash as the delimiter. https://stackoverflow.com/a/11245501/2520289
What is the proper syntax to do the exact same thing but with any of the other compatible delimiters for sed?
I have the delimiter changed for universal compatibility across most bash environments. (git-bash/any linux)
For example, I am currently doing the below snippet to replace any matches of the specific string but not the whole line.
function misc_findReplace()
{
VARIABLE_FIND="$1"
VARIABLE_REPLACE="$2"
VARIABLE_FILE="$3"
echo "Finding: $VARIABLE_FIND"
echo "Replacing With: $VARIABLE_REPLACE"
echo "File to Operate On: $VARIABLE_FILE"
sed -i "s@${VARIABLE_FIND}@c${VARIABLE_REPLACE}@g" "$VARIABLE_FILE"
}
FILE_TO_WORK_WITH="/path/to/my/file.properties"
STRING_TO_FIND="destination_hostname=<destination_hostname>"
STRING_TO_REPLACE="destination_hostname=localhost"
misc_findReplace "$STRING_TO_FIND" "$STRING_TO_REPLACE" "$FILE_TO_WORK_WITH"
Upvotes: 0
Views: 1391
Reputation: 71
To use different delimiters in sed, you want to escape the first occurance with a backslash.
such, the correct command would be
sed -i "\@${VARIABLE_FIND}@c${VARIABLE_REPLACE}" "$VARIABLE_FILE"
Upvotes: 3
Reputation: 182000
If I understand your question correctly, you have some text in a variable VARIABLE_FIND
which may contain slashes, and you want to replace all lines that contain that text by $VARIABLE_REPLACE
.
This sed
command will do that:
sed -i "/${VARIABLE_FIND//\//\\/}/c\\${VARIABLE_REPLACE}" "$VARIABLE_FILE"
It uses the same commands as in the answer you linked to but first escapes $VARIABLE_FIND
by replacing each /
character by \/
.
The way that's done is with bash
's construct ${var//search/replace}
, plus some extra backslashes for escaping inside double quotes.
Demo:
$ VARIABLE_FIND=/foo/
$ VARIABLE_REPLACE=This line has been replaced
$ echo -e 'some/foo/line\nsome/bar/line' | sed "/${VARIABLE_FIND//\//\\/}/c\\${VARIABLE_REPLACE}"
This line has been replaced
some/bar/line
Upvotes: 1