当来自 xargs 的 运行 时,如何避免来自 sed 的 "no input files" 错误?

How can I avoid "no input files" error from sed, when run from xargs?

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

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

如果 grep 命令没有找到匹配的文件,那么 sed 会抱怨 'no input files'。当文件列表为空时,如何使此管道成功?

如果你想避免 运行 sedgrep 没有输出时,那么(因为你已经用 Ubuntu 标记了它),你可以给出-r--no-run-if-empty 参数 xargs:

--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.

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

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