bash sed 错误“sed:不匹配的‘/’”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25057295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sed error "sed: unmatched '/'"
提问by MOHAMED
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 对文件进行了更改:
sed -i "/\<$param\>/s/.*/$line/" myfile
which line
variable is
哪个line
变量是
{"parameter":"toto.tata.titi", "value":"0/2", "notif":"3"}
and param
variable is toto.tata.titi
和param
变量是toto.tata.titi
The above sed
command return error:
上面的sed
命令返回错误:
sed: unmatched '/'
Because the line
variable is containing /
==> "0/2"
因为line
变量包含/
==>"0/2"
How to update my sed command to make it work even if the line
variable is containing /
?
即使line
变量包含,如何更新我的 sed 命令以使其工作/
?
回答by konsolebox
Your $param
or $line
may contain / on it which causes sed
to have a syntax error. Consider using other delimiters like |
or @
.
您的$param
或$line
可能包含 / 导致sed
语法错误。考虑使用其他分隔符,如|
或@
。
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
回答by SruthiChedath
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$//'
当我在 ansible 任务中使用 sed -i.bak 's/\r$//' 命令时,我遇到了同样的错误。我通过简单地转义“\r”中的“\”来解决它。我将命令更改为sed -i.bak 's/\\r$//'
回答by Ed Morton
This will robustly only operate on lines containing the string(not regexp) toto.tata.titi
:
这将仅在包含字符串(不是正则表达式)的行上稳健运行toto.tata.titi
:
awk -v param="$param" -v line="$line" 'index(awk 'BEGIN{param=ARGV[1]; line=ARGV[2]; ARGV[1]=ARGV[2]=""} index(##代码##,param){##代码## = line} 1' "$param" "$line" file
,param){##代码## = 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:
并且不受反斜杠中param
或line
反斜杠中的任何字符的影响。如果您需要能够按原样处理反斜杠,只需将 shell 变量移动到文件名列表中,并在 BEGIN 部分中从它们填充 awk 变量,而不是通过-v
赋值: