Linux or Unix find and remove files with one find command on fly

Q. How do I find and delete files under Linux / UNIX operating systems?

A. Some time it is necessary to find out files and remove them. However, rm command does not support search criteria.

However, with find command you can search for files in a directory and remove them on fly.

You need to combine find and rm command together.

Fortunately find command makes this operation quite easy. You can use find command as follows:

Linux or UNIX – Find and remove file syntax

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 first command can remove directories as well where second command only removes files.

More Examples of find command

(a) Find all files having .bak (*.bak) extension in current directory and remove them:
$ find . -type f -name "*.bak" -exec rm -f {} \;

(b) Find all core files and remove them:
# find / -name core -exec rm -f {} \;

(c) Find all *.bak files in current directory and removes them with confirmation from user:
$ find . -type f -name "*.bak" -exec rm -i {} \;

Output:

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

Caution: Before removing file makes sure, you have backup of all-important files. Do not use rm command as root user it can do critical damage to Linux/Unix system.

You can compress a HD with ‘dd’ on the fly like this;
dd if=/dev/sda1 |gzip > /backup-path/somename.img.gz
reverse looks like this;
gzip -dc /backup-path/somename.img.gz | dd of=/dev/sda1
If you backup your root partition always do it with a live-cd, as said by jahid65.
It is not smart to include a running /tmpfs that contains the thread of your dd command!

Gracias, Men

© 2017 Goose Workshop Suffusion theme by Sayontan Sinha