In a bash script I am working on to manipulate some configuration files, I have several fields working properly but one field that can take a double backslash config_item = "configfoo\\configbar"
as part of the configuration string.
I am reading in from the user with read -rp 'Configuration Item: ' config_item
Where it echos properly configfoo\\configbar
I've been unable to successfully land that into the sed command that updates the file.
sed -i -e '/config_item=/ s/=.*/='\"$config_item\"'/' ${dir}/.env
I get an error
sed: -e expression #1, char 19: unknown command: `\'
Which I assume is related to the 1st slash escaping. I've tried four slashes also trying to figure this out.
How do I tell sed to replace with the variable exactly as the user types it, or is there an alternative string preperation step I need to do so that my configuration file line reads
config_item = "configfoo\\configbar"
There are hundreds of posts on the topic, but I am not trying to substitute the slashes. I just need the string to flow into the substitution.
CodePudding user response:
If you absolutely don't want to escape your input string then you cannot use sed
; awk
is able to do it though:
awk '
BEGIN {
FS = OFS = "="
value = ARGV[2]
delete ARGV[2]
}
$1 == "config_item" { $0 = $1 OFS "\"" value "\"" }
1
' "$dir"/.env "$config_item" > "$dir"/.env.tmp &&
mv "$dir"/.env.tmp "$dir"/.env
CodePudding user response:
This might work for you (GNU sed and bash):
read -rp 'Configuration Item: ' config_item
export config_item
sed -Ei '/config_item\s*=/s/(.*=\s*).*/printf '\''\1"%s"'\'' "$config_item"/e' file
Read input into config_item variable.
Export config_item_variable.
Replace the entire line containing config_item =
and replace by config_item =
and the bash variable config_item.