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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:00:02  来源:igfitidea点击:

Sed error "sed: unmatched '/'"

linuxbashshellsed

提问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 linevariable is

哪个line变量是

{"parameter":"toto.tata.titi", "value":"0/2", "notif":"3"}

and paramvariable is toto.tata.titi

param变量是toto.tata.titi

The above sedcommand return error:

上面的sed命令返回错误:

sed: unmatched '/'

Because the linevariable is containing /==> "0/2"

因为line变量包含/==>"0/2"

How to update my sed command to make it work even if the linevariable is containing /?

即使line变量包含,如何更新我的 sed 命令以使其工作/

回答by konsolebox

Your $paramor $linemay contain / on it which causes sedto 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 paramor in lineother 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 -vassignment:

并且不受反斜杠中paramline反斜杠中的任何字符的影响。如果您需要能够按原样处理反斜杠,只需将 shell 变量移动到文件名列表中,并在 BEGIN 部​​分中从它们填充 awk 变量,而不是通过-v赋值:

##代码##