Sed replaces parameters such as paths

Problem description

To write the script, replace the path script in the JSON string as follows:

path=/root/baixw/test
​
sed -i "s/path=.*/path=$path/g" ./sed_path.txt
Copy the code

The script needs to replace the string with the path in the text. As a result, the script execution error occurs:

sed: -e expression #1, char 26: unknown option to 's'
Copy the code

Using the bash -x debug script, the sed command line is parsed as follows:

sed -i "s/path=.*/path=/root/baixw/test' ./sed_path.txt

The String has special characters that need to be escaped, so the result is very confusing

The solution

After Baidu, the following solutions are obtained:

path=/root/baixw/test sed -i "s? path=.*? path=$path? g" ./sed_path.txtCopy the code

The sed command has the following design: When it is inconvenient to escape special characters (such as /) in a string, sed supports custom delimiters to avoid collisions

That is, you can define characters that do not conflict. As above, I replaced? As a separator, it can also be a perfect solution to the problem