Issue
I am trying to modify a config file demo.cfg
from a .sh
file. I can modify it using sed
, but the problem is when the value contains slash character.
For that I am using this code:
read -r -p "(Default PATH: /my/default/path/): " response
case $response in
(*[![:blank:]]*) sed -i '/key_one/s/= ''.*/= '$response'/' demo.cfg; echo 'OK';;
(*) echo 'Using default path'
esac
Here the error when the variable $response
has slash:
sed: -e expression #1, char 20: unknown option to "s"
Could I scape this variable to use with sed function?
Here demo.cfg
file
[params]
key_one = 1
key_two = 9
Solution
Try passing response
like this
${response//\//\\/}
This replaces all /
with \/
. Example:
$ response=/my/path/to/target
$ echo ${response//\//\\/}
\/my\/path\/to\/target
There is also an issue with your case statement. Your bash script should look like this:
#!/bin/bash
read -r -p "(Default PATH: /my/default/path/): " response
case $response in
*[![:blank:]]*) sed -i "/key_one/s/= .*/= ${response//\//\\/}/" demo.cfg
echo 'OK'
;;
*) echo 'Using default path'
;;
esac
Answered By - user4918296 Answer Checked By - Katrina (WPSolving Volunteer)