At the moment his is what I do:

Step 1:

locate 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


  • Do you want this? rm -i locate fooBar`` – LFC_fan Dec 21 '10 at 14:24
  • I am not sure what the above does. I just want to remove all the files, from the paths that are returned when i run a locate command. – theTuxRacer Dec 22 '10 at 6:03

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'
  • 9
    To be robust against files with exotic characters (newlines, quotes, apostrophes, etc.) in their names, you can use the -0 (--null) option to locate and xargs. This uses the safe ASCII NUL character to separate filenames: locate -0 foobar | xargs -0 rm – Jukka Matilainen Dec 21 '10 at 16:02
  • 1
    +1 for the reply, and selected for mentioning the gotcha ^_^ – theTuxRacer Dec 22 '10 at 5:54
  • I tried it but it didn't work. – Pronoy Mukherjee Nov 15 '18 at 11:28
  • Worked partially – SteveS Jan 20 at 11:09

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

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

locate foobar | xargs rm -f

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.