不匹配时 sed 的返回值 [英] Return value of sed for no match
问题描述
我正在使用 sed
在运行时更新我的 JSON 配置文件.有时,当 JSON 文件中的模式不匹配时,sed
仍然以返回码 0 退出.
I'm using sed
for updating my JSON configuration file in the runtime.
Sometimes, when the pattern doesn't match in the JSON file, sed
still exits with return code 0.
返回 0 表示成功完成,但是如果 sed
没有找到正确的模式并更新文件,为什么它返回 0?有解决方法吗?
Returning 0 means successful completion, but why does sed
return 0 if it doesn't find the proper pattern and update the file? Is there a workaround for that?
推荐答案
正如@cnicutar 所评论的,命令的返回码表示命令是否成功执行.与您在代码/脚本中实现的逻辑无关.
as @cnicutar commented, the return code of a command means if the command was executed successfully. has nothing to do with the logic you implemented in the codes/scripts.
所以如果你有:
echo "foo"|sed '/bar/ s/a/b/'
sed 将返回 0
但如果你写了一些语法/表达式错误,或者输入/文件不存在,sed 无法执行你的请求,sed 将返回 1.
sed will return 0
but if you write some syntax/expression errors, or the input/file doesn't exist, sed cannot execute your request, sed will return 1.
解决方法
这实际上不是解决方法.sed 有 q
命令:(来自手册页):
this is actually not workaround. sed has q
command: (from man page):
q [exit-code]
在这里您可以根据需要定义退出代码.例如 '/foo/!{q100};如果
将以代码 100 退出,否则执行替换 f->b 并以代码 0 退出.foo
不存在,{s/f/b/}'
here you can define exit-code as you want. For example '/foo/!{q100}; {s/f/b/}'
will exit with code 100 if foo
isn't present, and otherwise perform the substitution f->b and exit with code 0.
匹配案例:
kent$ echo "foo" | sed '/foo/!{q100}; {s/f/b/}'
boo
kent$ echo $?
0
不匹配的情况:
kent$ echo "trash" | sed '/foo/!{q100}; {s/f/b/}'
trash
kent$ echo $?
100
我希望这能回答您的问题.
I hope this answers your question.
编辑
我必须补充一点,上面的例子仅用于单行处理.我不知道你的确切要求.当您想获得 exit 1
时.单行不匹配或整个文件.如果整个文件不匹配,你可以考虑 awk,甚至在你的文本处理之前做一个 grep
...
I must add that, the above example is just for one-line processing. I don't know your exact requirement. when you want to get exit 1
. one-line unmatched or the whole file. If whole file unmatching case, you may consider awk, or even do a grep
before your text processing...
这篇关于不匹配时 sed 的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!