Sed error “sed: unmatched '/'”

2019-07-18 02:47发布

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 /?

2条回答
【Aperson】
2楼-- · 2019-07-18 02:56

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
查看更多
Animai°情兽
3楼-- · 2019-07-18 03:09

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
查看更多
登录 后发表回答