Linux find all files and delete

How to find and delete directory recursively on Linux or Unix-like system

Find command syntax to delete directory recursively

Try the find command:
find /dir/to/search/ -type d -name «dirName» -exec rm -rf <> +
Another option is as follows to recursively remove folders on Linux or Unix:
find /dir/to/search/ -type d -name «dirName» -exec rm -rf \;

Warning : Be careful with the rm command when using with find. You may end up deleting unwanted data.

Find will execute given command when it finds files or dirs. For example:
find . -type d -name «foo» -exec rm -rf <> +
OR
find . -type d -name «bar» -exec rm -rf «<>» \;
Sample outputs:

You can find directories that are at least four levels deep in the working directory /backups/:
find /backups/ -type d -name «bar» -depth +4 -print0 -exec rm -rf <> +

Finding and deleting directory recursively using xargs

The syntax is as follows to find and delete directories on Linux/Unix system. For example, delete all empty directories:
find /path/to/dir/ -type d -empty -print0 | xargs -0 -I <> /bin/rm -rf «<>»
In this example, remove all foo directories including sub-diretories in /backups/ folder:
find /backups/ -type d -name «foo*» -print0 | xargs -0 -I <> /bin/rm -rf «<>»
The second command is a secure version. It is fast too, and it deals with weird directory names with white spaces and special characters in it:

Hence, I would like readers to use the following syntax:
find /path/to/search/ -name «pattern» -print0 | xargs -0 -I <> /bin/rm -rf «<>»
Where find command options are:

  • -name «pattern» : Base of file name that matches shell pattern pattern. For example, foo, Foo*3 and so on.
  • -print0 : Show the full file name on the standard output, followed by a null character. This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs

And xargs command options are:

  • -0 : Input items given by find are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode.
  • -I <> : <> in the initial-arguments with names read from standard input. For example, dir names given by find command./li>
  • /bin/rm -rf «<>« : Run rm command that remove files or directories passed by <> .

Shell script to recursively remove backups older than 30 days

Here is my sample script that removes older weekly backup of my VM tarballs stored in the following format:

Источник

Linux / Unix: Find and Delete All Empty Directories & Files

H ow do I find out all empty files and directories on a Linux / Apple OS X / BSD / Unix-like operating systems and delete them in a single pass?

You need to use the combination of find and rm command. [donotprint]

Tutorial details
Difficulty level Easy
Root privileges No
Requirements find command
Est. reading time 5m

[/donotprint]GNU/find has an option to delete files with -delete option. Please note that Unix / Linux filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by many utilities including rm command. To avoid problems you need to pass the -print0 option to find command and pass the -0 option to xargs command, which prevents such problems.

Method # 1: Find and delete everything with find command only

The syntax is as follows to find and delete all empty directories using BSD or GNU find command:

Find and delete all empty files:

Delete empty directories

In this example, delete empty directories from

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Delete empty files

In this example, delete empty files from

Fig.01: Delete empty directories and files.

How to count all empty files or directories?

The syntax is as follows:

  • -empty : Only find empty files and make sure it is a regular file or a directory.
  • -type d : Only match directories.
  • -type f : Only match files.
  • -delete : Delete files. Always put -delete option at the end of find command as find command line is evaluated as an expression, so putting -delete first will make find try to delete everything below the starting points you specified.

This is useful when you need to clean up empty directories and files in a single command.

Method # 2: Find and delete everything using xargs and rm/rmdir command

The syntax is as follows to find and delete all empty directories using xargs command:

Источник

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

However, the rm command does not support search criteria. For example, find all “*.bak” files and delete them. For such necessities, you need to use the find command to search for files in a directory and remove them on the fly. You can combine find and rm command together. This page explains how to find and remove files with one command on fly.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements find command
Est. reading time 4 minutes

Find And Remove Files With One Command On Fly

The basic find command syntax is as follows:
find dir-name criteria action
Where,

  1. dir-name : – Defines the working directory such as look into /tmp/
  2. criteria : Use to select files such as “*.sh”
  3. action : The find action (what-to-do on file) such as delete the file.

You want to remove multiple files such as ‘*.jpg’ or ‘*.sh’ with one command find, try:
find . -name «FILE-TO-FIND» -exec rm -rf <> \;
OR
find /dir/to/search/ -type f -name «FILE-TO-FIND-Regex» -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. Where, options are as follows:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

  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.
  4. -type d : Only match dirs and do not include files names.

Modern version of find command has -delete option too. Instead of using the -exec rm -rf <> \; , use the -delete to delete all matched files. We can also explicitly pass the -depth option to the find to process each directory’s contents before the directory itself. It is also possible to use the -maxdepth option to control descend at most levels of directories below the starting-points. For example, -maxdepth 0 means only apply the tests and actions to the starting-points themselves. Similary, we can pass the -mindepth to the find. It means do not apply any tests or actions at levels less than levels (a non-negative integer). For exampe, -mindepth 1 means process all files except the starting-points. So here is a simplied syntax:
find /dir/to/search/ -type f -name «FILES-TO-FIND» -delete
find /dir/to/search/ -type f -name «FILES-TO-FIND» -depth -delete
find /dir/to/search/ -maxdepth 2 -type f -name «FILES-TO-FIND» -depth -delete

Examples of find command

Find all files having .bak (*.bak) extension in the current directory and remove them:
find . -type f -name «*.bak» -exec rm -f <> \;
OR
find . -type f -name «*.bak» -delete
Find all core files in the / (root) directory and remove them (be careful with this command):
# find / -name core -exec rm -f <> \;
### OR ###
# find / -name core -delete
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:

The -delete always works better because it doesn’t have to spawn an external process such as rm for every matched file. However, the -delete option may not available on all find versions. Hence, we can use the xargs command as follows too:
find . -type f -name «*.err» -print0 | xargs -I <> -0 rm -v «<>»

Where the find command option is as follows:

  • -print0 – Force find command to print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs.

And the xargs command options are as follows:

  • -I <> : Replace occurrences of <> in the initial-arguments with names read from standard input. We pass <> as arg to the rm command.
  • -0 : Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode.
  • rm -v «<>« : Run rm command on matched files.

Conclusion

Read the following man pages using the man command:
man find
man xargs
man rm
For detailed information on find command please see finding/locating files with find command part # 1, Part # 2.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Команда find в Linux – мощный инструмент сисадмина

Иногда критически важно быстро найти нужный файл или информацию в системе. Порой можно ограничиться стандартами функциями поиска, которыми сейчас обладает любой файловый менеджер, но с возможностями терминала им не сравниться.

Команда find – это невероятно мощный инструмент, позволяющий искать файлы не только по названию, но и по:

  • Дате добавления.
  • Содержимому.
  • Регулярным выражениям.

Данная команда будет очень полезна системным администраторам для:

  • Управления дисковым пространством.
  • Бэкапа.
  • Различных операций с файлами.

Команда find в Linux производит поиск файлов и папок на основе заданных вами критериев и позволяет выполнять действия с результатами поиска.

Синтаксис команды find:

  • directory-to-search (каталог поиска) – это отправной каталог, с которой find начинает поиск файлов по всем подкаталогам, которые находятся внутри. Если не указать путь, тогда поиск начнется в текущем каталоге;
  • criteria (критерий) – критерий, по которым нужно искать файлы;
  • action (действие) – что делать с каждым найденным файлом, соответствующим критериям.

Поиск по имени

Следующая команда ищет файл s.txt в текущем каталоге:

  • . (точка) – файл относится к нынешнему каталогу
  • -name – критерии по которым осуществляется поиск. В данном случае поиск по названию файла.

В данном случае критерий -name учитывает только символы нижнего регистра и файл S.txt не появиться в результатах поиска. Чтобы убрать чувствительность к регистру необходимо использовать –iname.

Для поиска всех изображений c расширением .png нужно использовать шаблон подстановки *.png:

Можно использовать название каталога для поиска. Например, чтобы с помощью команды find найти все png изображения в каталоге home:

Если выдает слишком много ошибок в отказе разрешения, тогда можно добавить в конец команды – 2> /dev/null. Таким образом сообщения об ошибках будут перенаправляться по пути dev/null, что обеспечит более чистую выдачу.

Поиск по типу файла

Критерий -type позволяет искать файлы по типу, которые бывают следующих видов:

  • f – простые файлы;
  • d – каталоги;
  • l – символические ссылки;
  • b – блочные устройства (dev);
  • c – символьные устройства (dev);
  • p – именованные каналы;
  • s – сокеты;

Например, указав критерий -type d будут перечислены только каталоги:

Поиск по размеру файла

Допустим, что вам необходимо найти все большие файлы. Для таких ситуаций подойдет критерий -size.

  • «+» — Поиск файлов больше заданного размера
  • «-» — Поиск файлов меньше заданного размера
  • Отсутствие знака означает, что размер файлов в поиске должен полностью совпадать.

В данном случае поиск выведет все файлы более 1 Гб (+1G).

Единицы измерения файлов:

Поиск пустых файлов и каталогов

Критерий -empty позволяет найти пустые файлы и каталоги.

Поиск времени изменения

Критерий -cmin позволяет искать файлы и каталоги по времени изменения. Для поиска всех файлов, измененных за последний час (менее 60 мин), нужно использовать -60:

Таким образом можно найти все файлы в текущем каталоге, которые были созданы или изменены в течение часа (менее 60 минут).

Для поиска файлов, которые наоборот были изменены в любое время кроме последнего часа необходимо использовать +60.

Поиск по времени доступа

Критерий -atime позволяет искать файлы по времени последнего доступа.

Таким образом можно найти файлы, к которым не обращались последние полгода (180 дней).

Поиск по имени пользователя

Опция –user username дает возможность поиска всех файлов и каталогов, принадлежащих конкретному пользователю:

Таким образом можно найти все файлы пользователя tisha в каталоге home, а 2>/dev/null сделает выдачу чистой без ошибок в отказе доступа.

Поиск по набору разрешений

Критерий -perm – ищет файлы по определенному набору разрешений.

Поиск файлов с разрешениями 777.

Операторы

Для объединения нескольких критериев в одну команду поиска можно применять операторы:

Например, чтобы найти файлы размером более 1 Гбайта пользователя tisha необходимо ввести следующую команду:

Если файлы могут принадлежать не только пользователю tisha, но и пользователю pokeristo, а также быть размером более 1 Гбайта.

Перед скобками нужно поставить обратный слеш «\».

Действия

К команде find можно добавить действия, которые будут произведены с результатами поиска.

  • -delete — Удаляет соответствующие результатам поиска файлы
  • -ls — Вывод более подробных результатов поиска с:
    • Размерами файлов.
    • Количеством inode.
  • -print Стоит по умолчанию, если не указать другое действие. Показывает полный путь к найденным файлам.
  • -exec Выполняет указанную команду в каждой строке результатов поиска.

-delete

Полезен, когда необходимо найти и удалить все пустые файлы, например:

Перед удалением лучше лишний раз себя подстраховать. Для этого можно запустить команду с действием по умолчанию -print.

Данное действие является особенным и позволяет выполнить команду по вашему усмотрению в результатах поиска.

  • command – это команда, которую вы желаете выполнить для результатов поиска. Например:
    • rm
    • mv
    • cp
  • <> – является результатами поиска.
  • \; — Команда заканчивается точкой с запятой после обратного слеша.

С помощью –exec можно написать альтернативу команде –delete и применить ее к результатам поиска:

Другой пример использования действия -exec:

Таким образом можно скопировать все .jpg изображения в каталог backups/fotos

Заключение

Команду find можно использовать для поиска:

  • Файлов по имени.
  • Дате последнего доступа.
  • Дате последнего изменения.
  • Имени пользователя (владельца файла).
  • Имени группы.
  • Размеру.
  • Разрешению.
  • Другим критериям.

С полученными результатами можно сразу выполнять различные действия, такие как:

  • Удаление.
  • Копирование.
  • Перемещение в другой каталог.

Команда find может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.

Источник

Читайте также:  Linux xterm font size
Оцените статью