Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I'm trying to write a bash command that will delete all files matching a specific pattern - in this case, it's all of the old vmware log files that have built up.

I've tried this command:

find . -name vmware-*.log | xargs rm

However, when I run the command, it chokes up on all of the folders that have spaces in their names. Is there a way to format the file path so that xargs passes it to rm quoted or properly escaped?

share|improve this question
    
Cross-posted: stackoverflow.com/questions/1590297/… –  Dennis Williamson Oct 19 '09 at 20:18

4 Answers 4

up vote 18 down vote accepted

I generally find that using the -exec option for find to be easier and less confusing. Try this:

find . -name vmware-*.log -exec rm -i {} \;

Everything after -exec is taken to be a command to run for each result, up to the ;, which is escaped here so that it will be passed to find. The {} is replaced with the filename that find would normally print.

Once you've verified it does what you want, you can remove the -i.

share|improve this answer
1  
Also, if it's just files you want to delete and not directories, you can add ''-type f'' to the find command. –  JamesHannah Oct 19 '09 at 19:13

You can tell find to delimit the output list with NULLs, and xargs to receive its input list the same:

$ ls -l "file 1" "file 2"
-rw-r--r-- 1 james james 0 Oct 19 13:28 file 1
-rw-r--r-- 1 james james 0 Oct 19 13:28 file 2

$ find . -name 'file *' -print0 | xargs -0 ls -l
-rw-r--r-- 1 james james 0 Oct 19 13:28 ./file 1
-rw-r--r-- 1 james james 0 Oct 19 13:28 ./file 2

$ find . -name 'file *' -print0 | xargs -0 rm -v
removed `./file 2'
removed `./file 1'

Also, make sure you escape the *, either with a backslash, or by containing the vmware-*.log in single quotes, otherwise your shell may try to expand it before passing it off to find.

share|improve this answer

Dont't forget the find's -delete option. It remove the file without error with special characters...

share|improve this answer

If you have GNU find you can use the -delete option:

find . -name "vmware-*.log" -delete

To use xargs and avoid the problem with spaces in filenames:

find . -name vmware-*.log -print0 | xargs -0 rm

However, your log files shouldn't have spaces in their names. Word processing documents and MP3 files are likely to have them, but you should be able to control the names of your log files.

share|improve this answer
    
That's neat. I didn't know about that. –  Jeff Snider Oct 19 '09 at 19:13

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.