Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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.

share|improve this question
    
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

3 Answers 3

up vote 7 down vote accepted

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'
share|improve this answer
4  
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 for the reply, and selected for mentioning the gotcha ^_^ –  theTuxRacer Dec 22 '10 at 5:54

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
share|improve this answer

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

locate foobar | xargs rm -f

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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