19

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.

theTuxRacer
  • 16,533

4 Answers4

18

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'
finley
  • 2,095
9

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
qbi
  • 19,515
7

To delete all the files that are returned by locate,issue the following command in your terminal

locate foobar | xargs rm -f

karthick87
  • 84,513
0

A less succinct alternative is to use a loop with command substitution:

for file in $(locate foobar); do rm "$file"; done

The $(locate foobar) bit uses the output of the locate foobar, then the for loop allows you do run something on each line of this. The quotes around $file should allow this to work with spaces in filenames.

Although xargs is more concise, the loop might be better suited if you want to expand the logic, for example, running multiple commands within the loop.

As others have suggested, either run locate foofar first or add the -i option to rm to avoid doing something really bad and deleting a file you didn't mean to delete

moo
  • 966