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 -rlZ "$old" /etc | xargs -0 -r sed -i "s/$old/$new/g"
(I added grep -Z
and xargs -0
flags, since these are supported on your platform, and they make the commands more robust to malicious filenames)
For platforms without xargs -r
, then the usual solution is to pass /dev/null
as a first filename argument:
grep -rl "$old" /etc | xargs sed -i "s/$old/$new/g" /dev/null
In this case, when there are no matches, sed
will operate harmlessly on the null device.