Linux / Unix: Find And Remove Files With One Command On Fly

To remove multiple files such as *.jpg or *.sh with one command find, use:

find . -name “FILE-TO-FIND” -exec rm -rf {} \;

OR

find . -type f -name “FILE-TO-FIND” -exec rm -f {} \;

The only difference between above two syntax is that the first command
remove directories as well where second command only removes files. Options:

1. *-name “FILE-TO-FIND”* : File pattern.
2. *-exec rm -rf {} \;* : Delete all files matched by file pattern.
3. *-type f* : Only match files and do not include directory names.

$ find . -type f -name “*.bak” -exec rm -f {} \;

Find all core files in the / (root) directory and remove them (be careful
with this command):
# find / -name core -exec rm -f {} \;

Find all *.bak files in the current directory and removes them with
confirmation from user:
$ find . -type f -name “*.bak” -exec rm -i {} \;
Sample outputs:

rm: remove regular empty file `./data0002.bak’? y
rm: remove regular empty file `./d234234234fsdf.bak’? y
rm: remove regular empty file `./backup-20-10-2005.bak’? n

Source : cyberciti

Revisions

No comments yet.

Leave a Reply