Reputation: 43598
I have a file containing data with the following format:
{"parameter":"toto.tata.titi", "value":"0/2", "notif":"1"}
I make a change on the file with sed:
sed -i "/\<$param\>/s/.*/$line/" myfile
which line
variable is
{"parameter":"toto.tata.titi", "value":"0/2", "notif":"3"}
and param
variable is toto.tata.titi
The above sed
command return error:
sed: unmatched '/'
Because the line
variable is containing /
==> "0/2"
How to update my sed command to make it work even if the line
variable is containing /
?
Upvotes: 5
Views: 25286
Reputation: 31
Check if your $param
or $line
variables have \n
(newline), in my case, that was the reason of the error.
Upvotes: 1
Reputation: 431
i had the same error when i used sed -i.bak 's/\r$//' command in my ansible task. i solved it by simply escaping the '\' in '\r'. i changed the command to sed -i.bak 's/\\r$//'
Upvotes: 0
Reputation: 204558
This will robustly only operate on lines containing the string (not regexp) toto.tata.titi
:
awk -v param="$param" -v line="$line" 'index($0,param){$0 = line} 1' file
and will be unaffected by any chars in param
or in line
other than backslashes. If you need to be able to process backslashes as-is, the shell variables just need to be moved to the file name list and the awk variables populated from them in the BEGIN section instead of by -v
assignment:
awk 'BEGIN{param=ARGV[1]; line=ARGV[2]; ARGV[1]=ARGV[2]=""} index($0,param){$0 = line} 1' "$param" "$line" file
Upvotes: -1
Reputation: 75588
Your $param
or $line
may contain / on it which causes sed
to have a syntax error. Consider using other delimiters like |
or @
.
Example:
sed -i "/\<$param\>/s|.*|$line|" myfile
But that may not be enough. You can also quote your slashes when they expand:
sed -i "/\<${param//\//\\/}\>/s|.*|$line|" myfile
Other safer characters can be used too:
d=$'\xFF' ## Or d=$(printf '\xFF') which is compatible in many shells.
sed -i "/\<${param//\//\\/}\>/s${d}.*${d}${line}${d}" myfile
Upvotes: 9