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

时光毁灭记忆、已成空白 提交于 2019-12-08 17:59:08

问题


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"

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?


回答1:


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


来源:https://stackoverflow.com/questions/35431718/how-can-i-avoid-no-input-files-error-from-sed-when-run-from-xargs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!