如何避免“无输入文件"?来自 sed 的错误,当从 xargs 运行时? [英] How can I avoid "no input files" error from sed, when run from xargs?

查看:47
本文介绍了如何避免“无输入文件"?来自 sed 的错误,当从 xargs 运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 shell 脚本来更新我的配置文件中的 IP 地址(任何匹配 $old_address_pattern 必须更改为 $new_address):

I have this shell script to update IP addresses in my configuration files (any that match $old_address_pattern must be changed to $new_address):

grep -rl "$old_address_pattern" /etc \
  | xargs sed -i "s/$old_address_pattern/$new_address/g"

如果 grep 命令没有找到匹配的文件,那么 sed 将抱怨没有输入文件".当文件列表为空时,如何使此管道成功?

If the grep command finds no matching files, then sed will complain 'no input files'. How can I make this pipeline succeed when the list of files is empty?

推荐答案

如果你想避免在 grep 没有输出时运行 sed,那么(因为你已经用 Ubuntu 标记),你可以给 -r--no-run-if-emptyxargs 的参数:

If you want to avoid running sed when grep produces no output, then (since you've tagged this with Ubuntu), you can give the -r or --no-run-if-empty argument to xargs:

--no-run-if-empty
-r
如果标准输入不包含任何非空格,请不要运行该命令.通常,即使没有输入,命令也会运行一次.此选项是 GNU 扩展.

--no-run-if-empty
-r
If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension.

所以你的命令应该是这样的:

So your command should look like:

grep -rl "$old" /etc | xargs -r sed -i "s/$old/$new/g"

这篇关于如何避免“无输入文件"?来自 sed 的错误,当从 xargs 运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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