Linux – How to use find command to delete files matching a pattern

bashfindlinuxlog-filesshell-scripting

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?

Best Answer

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.