How to delete all files that are returned by locate
At the moment his is what I do:
Step 1:
locate fooBar
/home/abc/fooBar
/home/abc/Music/fooBar
Step 2:
Manually perform a removal, by copy-pasting each line.
rm /home/abc/fooBar
rm /home/abc/Music/fooBar
How do I do this in one step? Something like
locate fooBar > rm
Thanks.
As the other chaps have already mentioned, xargs is your friend. It's a really powerful tool and I'll try to explain it and provide a workaround for a common gotcha.
What xargs does is take a line from the input, and append it to another command, executing that other command for every line in the input. So by typing locate foobar | xargs rm -f
, the output of the locate command will be patched onto the end of the rm -f
command, and executed for each line produced by locate foobar
.
The gotcha:
But what if there are spaces in your line(s) returned by locate? That will break the rm -f
command because the arguments passed to rm need to be files (unless you use the -r switch), and a file-path needs to be escaped or quoted if it contains spaces.
xargs provides the -i switch, to substitute the input into the command that follows instead of just appending it. So I'd change the suggestion to
locate foobar | xargs -ixxx rm -f 'xxx'
which will now only break if the filenames returned by locate contained apostrophes.
I have to concur with qbi, that you should be careful about using rm -f ! Use the -p flag to xargs, or just run the locate foobar by itself before feeding it to xargs, or drop the -f from rm.
locate foobar | xargs -p -ixxx rm -f 'xxx'
You maybe need some more options for use with xargs
. Test it first with xargs -p
. If it is OK, remove the -p
option:
locate foobar | xargs rm