sed的返回码不匹配 [英] Return code of sed for no match

查看:274
本文介绍了sed的返回码不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sed在运行时中更新我的json配置文件. 有时候,当json文件中的模式不匹配时,sed仍会以返回代码0退出.

I'm using sed for updating my json configuration file in the runtime. Sometimes, when the pattern doesn't matches in the json file, still sed exits with return code 0.

返回0表示成功完成,但是为什么sed如果找不到正确的模式并更新文件,为什么返回0?有解决方法吗?

Returning 0 means successful completion, but why does sed returns 0 if it doesnt 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不存在,则'/foo/!{q100}; {s/f/b/}'将以代码100退出,否则执行替换f-> b并以代码0退出.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆