How to find and remove files in Ubuntu.

Menaka Jayawardena
2 min readMar 14, 2017

Hi,

Sometimes we want to find the files that are not needed and remove all of them. But instead of removing one by one, we can do it very easily with one command.

Work flow.

I needed to remove all the .iml files in my project for a deployment. So I executed a find command.

find . -name '*.iml'./SenseMe/feature/feature/org.wso2.iot.senseme.feature.iml
./SenseMe/feature/senseme-feature.iml
./SenseMe/senseme.iml
./SenseMe/component/plugin/org.wso2.iot.senseme.plugin.iml
./SenseMe/component/ui/org.wso2.iot.senseme.ui.iml
./SenseMe/component/api/org.wso2.iot.senseme.api.iml
./SenseMe/component/senseme-component.iml
./SenseMe/component/analytics/org.wso2.iot.senseme.analytics.iml'
Now, I want to remove these files.
rm ./SenseMe/feature/feature/org.wso2.iot.senseme.feature.imlRepeat for all the other files. It's not a big issue as I have only 8 files. But in real cases where there are 100s of files, it is a real headache.rm ./SenseMe/feature/senseme-feature.iml
rm ./SenseMe/senseme.iml
rm ./SenseMe/component/plugin/org.wso2.iot.senseme.plugin.iml
rm ./SenseMe/component/ui/org.wso2.iot.senseme.ui.iml
rm ./SenseMe/component/api/org.wso2.iot.senseme.api.iml
rm ./SenseMe/component/senseme-component.iml
rm ./SenseMe/component/analytics/org.wso2.iot.senseme.analytics.iml
But, there is an easy way to do this. How easy is it? Well, you only have to write one line of commands. :-)find . -name '*.iml' -exec rm {} \;UPDATE : Replaced \ ; with \;
There should be no space between \ and ;.
What is does?
  • find . -name ‘*.iml’ :- Find in the current directory for files which matches the given pattern.
  • -exec rm {} \ ; :- Executes rm command on each of the results from find command.

Note:
You can use standard ways of find and rm commands and -exec does the execution.

Examples:
Find all files in a directory and remove them.

find . -type f -name ‘File Name Pattern’ -exec rm {} \ ;

Find directories and remove them

find . -name ‘File/ Dir Name Pattern’ -exec rm -rf {} \ ;

For more info: please refer command reference for find and rm.
Cheers.

--

--