- Using find — Deleting all files/directories (in Linux ) except any one
- 11 Answers 11
- Find Command in Linux (Find Files and Directories)
- find Command Syntax #
- Find Files by Name #
- Find Files by Extension #
- Find Files by Type #
- Find Files by Size #
- Find Files by Modification Date #
- Find Files by Permissions #
- Find Files by Owner #
- Find and Delete Files #
- Conclusion #
Using find — Deleting all files/directories (in Linux ) except any one
If we want to delete all files and directories we use, rm -rf * . But what if i want all files and directories be deleted at a shot, except one particular file? Is there any command for that? rm -rf * gives the ease of deletion at one shot, but deletes even my favourite file/directory. Thanks in advance
11 Answers 11
find can be a very good friend:
$ ls a/ b/ c/ $ find * -maxdepth 0 -name 'b' -prune -o -exec rm -rf '<>' ';' $ ls b/ $
- find * -maxdepth 0 : select everything selected by * without descending into any directories
- -name ‘b’ -prune : do not bother ( -prune ) with anything that matches the condition -name ‘b’
- -o -exec rm -rf ‘<>‘ ‘;’ : call rm -rf for everything else
By the way, another, possibly simpler, way would be to move or rename your favourite directory so that it is not in the way:
$ ls a/ b/ c/ $ mv b .b $ ls a/ c/ $ rm -rf * $ mv .b b $ ls b/
@maveric: agreed, that’s how I’d write it, but I’d rather not get into the various shell intricacies involving quoting and escaping in this answer.
Could you not generate the list of files excluding the file to be «protected» and then pipe it to xargs rather than spawning rm for every match using -exec ?
@Noufal: not portably — many xargs variants out there do not have -0 which tends to make things easier when dealing with whitespace.
Short answer
ls | grep -v "z.txt" | xargs rm
The thought process for the above command is :
- List all files (ls)
- Ignore one file named «z.txt» (grep -v «z.txt»)
- Delete the listed files other than z.txt (xargs rm)
Create 5 files as shown below:
echo "a.txt b.txt c.txt d.txt z.txt" | xargs touch
List all files except z.txt
ls|grep -v "z.txt" a.txt b.txt c.txt d.txt
We can now delete(rm) the listed files by using the xargs utility :
You can type it right in the command-line or use this keystroke in the script
files=`ls -l | grep -v "my_favorite_dir"`; for file in $files; do rm -rvf $file; done
P.S. I suggest -i switch for rm to prevent delition of important data.
P.P.S You can write the small script based on this solution and place it to the /usr/bin (e.g. /usr/bin/rmf ). Now you can use it as and ordinary app:
The script looks like (just a sketch):
#!/bin/sh if [[ -z $1 ]]; then files=`ls -l` else files=`ls -l | grep -v $1` fi; for file in $files; do rm -rvi $file done;
Hmmm, parsing the output of ls is not a good idea — it’s a bad habit that should not be propagated to others. And your for loops will have issues with filenames that include whitespace.
could be an option, if you only want to preserve one single file.
If it’s just one file, one simple way is to move that file to /tmp or something, rm -Rf the directory and then move it back. You could alias this as a simple command.
The other option is to do a find and then grep out what you don’t want (using -v or directly using one of find s predicates) and then rm ing the remaining files.
For a single file, I’d do the former. For anything more, I’d write something custom similar to what thkala said.
In bash you have the !() glob operator, which inverts the matched pattern. So to delete everything except the file my_file_name.txt , try this:
shopt -s extglob rm -f !(my_file_name.txt)
I don’t know of such a program, but I have wanted it in the past for some times. The basic syntax would be:
IFS=' ' for f in $(except "*.c" "*.h" -- *); do printf '%s\n' "$f" done
The program I have in mind has three modes:
- exact matching (with the option -e )
- glob matching (default, like shown in the above example)
- regex matching (with the option -r )
It takes the patterns to be excluded from the command line, followed by the separator — , followed by the file names. Alternatively, the file names might be read from stdin (if the option -s is given), each on a line.
Such a program should not be hard to write, in either C or the Shell Command Language. And it makes a good excercise for learning the Unix basics. When you do it as a shell program, you have to watch for filenames containing whitespace and other special characters, of course.
Find Command in Linux (Find Files and Directories)
The find command is one of the most powerful tools in the Linux system administrators arsenal. It searches for files and directories in a directory hierarchy based on a user given expression and can perform user-specified action on each matched file.
You can use the find command to search for files and directories based on their permissions, type, date, ownership, size, and more. It can also be combined with other tools such as grep or sed .
find Command Syntax #
The general syntax for the find command is as follows:
find [options] [path. ] [expression]
- The options attribute controls the treatment of the symbolic links, debugging options, and optimization method.
- The path. attribute defines the starting directory or directories where find will search the files.
- The expression attribute is made up of options, search patterns, and actions separated by operators.
To search for files in a directory, the user invoking the find command needs to have read permissions on that directory.
Let’s take a look at the following example:
- The option -L (options) tells the find command to follow symbolic links.
- The /var/www (path…) specifies the directory that will be searched.
- The (expression) -name «*.js tells find to search files ending with .js (JavaScript files).
Find Files by Name #
Finding files by name is probably the most common use of the find command. To find a file by its name, use the -name option followed by the name of the file you are searching for.
For example, to search for a file named document.pdf in the /home/linuxize directory, you would use the following command:
find /home/linuxize -type f -name document.pdf
To run a case-insensitive search, change the -name option with -iname :
find /home/linuxize -type f -iname document.pdf
The command above will match “Document.pdf”, “DOCUMENT.pdf” ..etc.
Find Files by Extension #
Searching for files by extension is the same as searching for files by name. For example, to find all files ending with .log.gz inside the /var/log/nginx directory, you would type:
find /var/log/nginx -type f -name '*.log.gz'
It is important to mention that you must either quote the pattern or escape the asterisk * symbol with backslash \ so that it doesn’t get interpreted by the shell when you use the wildcard character.
To find all files that don’t match the regex *.log.gz you can use the -not option. For example, to find all files that don’t end in *.log.gz you would use:
find /var/log/nginx -type f -not -name '*.log.gz'
Find Files by Type #
Sometimes you might need to search for specific file types such as regular files, directories, or symlinks. In Linux, everything is a file.
To search for files based on their type, use the -type option and one of the following descriptors to specify the file type:
- f : a regular file
- d : directory
- l : symbolic link
- c : character devices
- b : block devices
- p : named pipe (FIFO)
- s : socket
For instance, to find all directories in the current working directory , you would use:
The common example would be to recursively change the website file permissions to 644 and directory permissions to 755 using the chmod command:
find /var/www/my_website -type d -exec chmod 0755 <> \;
find /var/www/my_website -type f -exec chmod 0644 <> \;
Find Files by Size #
To find files based on the file size, pass the -size parameter along with the size criteria. You can use the following suffixes to specify the file size:
- b : 512-byte blocks (default)
- c : bytes
- w : two-byte words
- k : Kilobytes
- M : Megabytes
- G : Gigabytes
The following command will find all files of exactly 1024 bytes inside the /tmp directory:
find /tmp -type f -size 1024c
The find command also allows you to search for files that are greater or less than a specified size.
In the following example, we search for all files less than 1MB inside the current working directory. Notice the minus — symbol before the size value:
If you want to search for files with a size greater than 1MB , then you need to use the plus + symbol:
You can even search for files within a size range. The following command will find all files between 1 and 2MB :
find . -type f -size +1M -size 21M
Find Files by Modification Date #
The find command can also search for files based on their last modification, access, or change time.
Same as when searching by size, use the plus and minus symbols for “greater than” or “less than”.
Let’s say that a few days ago, you modified one of the dovecot configuration files, but you forgot which one. You can easily filter all files under the /etc/dovecot/conf.d directory that ends with .conf and has been modified in the last five days:
find /etc/dovecot/conf.d -name "*.conf" -mtime 5
Here is another example of filtering files based on the modification date using the -daystart option. The command below will list all files in the /home directory that were modified 30 or more days ago:
find /home -mtime +30 -daystart
Find Files by Permissions #
The -perm option allows you to search for files based on the file permissions.
For example, to find all files with permissions of exactly 775 inside the /var/www/html directory, you would use:
You can prefix the numeric mode with minus — or slash / .
When slash / is used as the prefix, then at least one category (user, group, or others) must have at least the respective bits set for a file to match.
Consider the following example command:
The above command will match all the files with read permissions set for either user, group, or others.
If minus — is used as the prefix, then for the file to match, at least the specified bits must be set. The following command will search for files that have read and write permission for the owner and group and are readable by other users:
Find Files by Owner #
To find files owned by a particular user or group, use the -user and -group options.
For example, to search for all files and directories owned by the user linuxize , you would run:
Here is a real-world example. Let’s say you want to find all files owned by the user www-data and change the ownership of the matched files from www-data to nginx :
find / -user www-data -type f -exec chown nginx <> \;
Find and Delete Files #
To delete all matching files, append the -delete option to the end of the match expression.
Ensure you are using this option only when you are confident that the result matches the files you want to delete. It is always a good idea to print the matched files before using the -delete option.
For example, to delete all files ending with .temp from the /var/log/ , you would use:
find /var/log/ -name `*.temp` -delete
Use the -delete option with extreme caution. The find command is evaluated as an expression and if you add the -delete option first, the command will delete everything below the starting points you specified.
When it comes to directories, find can delete only empty directories, same as rmdir .
Conclusion #
We have shown you how to use the find command with various options and criteria.
This article should give you a fundamental understanding of how to locate files on your Linux systems. You may also visit the find man page and read about all other powerful options of the find command.
If you have any questions or remarks, please leave a comment below.