- Find Command Exclude Directories From Search Pattern
- Find command Exclude or Ignore Files (e.g. Ignore All Hidden .dot Files )
- Find command exclude or ignore files syntax
- Examples: find command and logical operators
- Understanding find command operators
- How do I ignore hidden .dot files while searching for files?
- Say hello to -path option
- Exclude a directory or multiple directories while using find command
- Method 1 : Using the option “-prune -o”
- Method 2 : Using “! -path”
- Method 3 : Simple 🙂
- Excluding multiples directories
- Linux find exclude pattern
- Команда find в Linux – мощный инструмент сисадмина
- Поиск по имени
- Поиск по типу файла
- Поиск по размеру файла
- Единицы измерения файлов:
- Поиск пустых файлов и каталогов
- Поиск времени изменения
- Поиск по времени доступа
- Поиск по имени пользователя
- Поиск по набору разрешений
- Операторы
- Действия
- -delete
- Заключение
Find Command Exclude Directories From Search Pattern
H ow do I exclude certain directories while using the find command under UNIX or Linux operating systems?
You can use the find command as follows to find all directories except tmp directory:
Find all directories except tmp and cache:
The -prune option make sure that you do not descend into directory:
- 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 ➔
You can find all *.pl find except in tmp and root directory, enter:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
find / \( ! -name tmp \) -o \( ! -name root -prune \) -name “*.pl” -print
it’s also displaying the files in tmp directory ?? this isn’t working
using findutils.x86_64 1:4.2.27-6.el5 version
On my Ubuntu 11 this command will search for all “pl” files in the entire / dir but will not descend in /tmp:
find . -path ./tmp -prune -o -iname “**.pl” -print
To exclude multiple directories, the option to use is -a, which is AND operation; not -o as listed in the above article.
Therefore, to find all directories except tmp and cache
find /path/to/dest -type d \( ! -name tmp \) -a \( ! -name cache \) -print
we have the below directory structure:
/secure/data/bus/PREP_MDATA/preserve
/secure/data/bus/PREP_TDATA/preserve
/secure/data/bus/PREP_QDATA/preserve
/secure/data/bus/PREP_RDATA/preserve
I want to exclude the below 2 directories from my search but show up the other 2
/secure/data/bus/PREP_TDATA/preserve
/secure/data/bus/PREP_QDATA/preserve
How do I do that using the above stated commands.
Thanks for the help
I’m just trying to exclude ONE directory, and the code doesn’t work. All directories are printed.
Joe,
Try this
This will list a non case sensitive list of all files with some phrase but will exlude some other folder with some non case sensitive phrase in it.
Remember if you just want it to list all files you can use * or *.ext for all files with .ext etc.
It seems counter intuitive to use the -o flag but it works here on csh
The dot right after the find command signifies THIS directory or whatever directory you are in. You can always replace that with another directory path.
find . -type f -iname “insert_file_names_you_want_listed_here” -print -o -type d -iname “insert_folder_name_you_dont_want_here” -prune
Chris, thanks a lot, due to your post I was able to search for files containing “somephrase” in directory and its subdirs excluding some speciffic subdirectories with this command:
find /path/to/dir/ -exec grep -q somephrase <> \; -print -o -type d -wholename “/path/to/dir/speciffic/dir/*” -prune
hopefully somebody will find it usefull
find . \( -name results -prune \) -o \( -name typ_testout -prune \) -o \( -name obj-testgen -prune \) -o \( -name obj-sim -prune \) -o -type f -exec grep -w abf <> \; -print
I was trying to find the list of files having the string “abf”. But I wanted to exclude search results in the “results”, “typ_testout”, “obj-testgen”,”obj-sim” directories. So I used the above command and it worked perfectly fine for me. The secret is the “-o” option after each expression. So the find command matches against multiple expressions.
Thanks for the article, using it and the man page, here is a version using wholename to ‘prune’ absolute paths:
find all directories except tmp directory:
find /path/to/dest -maxdepth 2 -type d \( ! -name tmp \) -print
how about show only the directory with no subtmp?
find . -name “*.mp3” -and -not -path “*Trash*”
will find all mp3 files and exclude any folder containing the letters “Trash”
+++ thank you, been looking to exclude my .svn folder when using find — this did the trick: find . -type f -and -not -path “*.svn*” -print
The real general problem is that of excluding certain directories by name, *AND ALSO AVOIDING TRAVERSING THEM* because they may contain *HUGE* subtrees that would take ages to scan, which is *PRECISELY* why we want to exclude them.
Additionally, the directories to be excluded may be located deeper than immediately below the start directory, i.e. if the intention is to exclude directories namet _thumb, then *ALL* of the following should be excluded:
./_thumb
./customer1/_thumb
./customer2/website4/_thumb
The answers above either don’t work at all, fail to avoid traversing the excluded directories, or would only exclude the first line.
Is the solution satisfying *ALL* the above requirements even possible with find?
Due to some bugs and versions of find, some works and not.
Though a simle find with grep will do.
Find the files and directories with ganglia on it, except for the directories with name Downloads.
sudo find / -iname “*ganglia*” | egrep -vi “downloads”
Or you can exclude specific directory like, find files or directories with ganglia except in the directory /home/simpleboy/Downloads
sudo find / -iname “*ganglia*” | egrep -v “\/home\/simpleboy\/Downloads”
Thanks More power nixCraft!
find / \( -path /exclude-folder1 -o -path /exclude-folder2 \) -prune -or -iname ‘*look-up*’ -exec ls -ld <> \;
Источник
Find command Exclude or Ignore Files (e.g. Ignore All Hidden .dot Files )
Find command exclude or ignore files syntax
The syntax is as follows:
Examples: find command and logical operators
Find any file whose name ends with either ‘c’ or ‘asm’, enter:
$ find . -type f \( -iname «*.c» -or -iname «*.asm» \)
In this example, find all *.conf and (.txt) text files in the /etc/ directory:
$ find . -type f \( -name «*.conf» -or -name «*.txt» \) -print
Fig.01: Linux find command exclude files command
Understanding find command operators
Operators build a complex expression from tests and actions. The operators are, in order of decreasing precedence:
( expr ) | Force precedence. True if expr is true |
expr -not expr ! expr | True if expr is false. In some shells, it is necessary to protect the ‘!’ from shell interpretation by quoting it. |
expr1 -and expr2 | expr2 is not evaluated if expr1 is false. |
expr1 -or expr2 | expr2 is not evaluated if expr1 is true. |
How do I ignore hidden .dot files while searching for files?
Find *.txt file but ignore hidden .txt file such as .vimrc or .data.txt file:
$ find . -type f \( -iname «*.txt» ! -iname «.*» \)
Find all .dot files but ignore .htaccess file:
$ find . -type f \( -iname «.*» ! -iname «.htaccess» \)
Say hello to -path option
This option return true if the pathname being examined matches pattern. For example, find all *.txt files in the current directory but exclude ./Movies/, ./Downloads/, and ./Music/ folders:
Источник
Exclude a directory or multiple directories while using find command
Table of Contents
Is it possible to exclude a directory with find command? Exclude directories while doing running find command?
Yep, the command FIND has wide range of options to search what you actually looking for. I have already listed different switches and its usages with examples. Here we go for excluding some directories from our find job.
In some cases, we have to exclude some directories from our search pattern to improve the search speed or efficiency. If the server has a lot of directories and we are sure about that the file / directory that we are searching is not in some directories, we can directly exclude those to improve the performance. The result will be faster as compared to the full search.
There are different ways to exclude a directory or multiple directories in FIND command. Here I’m listing some methods!
To explain this, I created the following directories and files:
- “cry“, “bit” and “com” directories.
- ” findme “: The test file in all directories.
Lets see the output:
Method 1 : Using the option “-prune -o”
We can exclude directories by using the help of “path“, “prune“, “o” and “print” switches with find command.
See the example:
The directory “bit” will be excluded from the find search!
Method 2 : Using “! -path”
This is not much complicated compared to first method. See the example pasted below:
Method 3 : Simple 🙂
Yes, it’s very simple. We can ignore the location by using inverse grep “grep -v” option.
See the example:
Excluding multiples directories
Similar way we can exclude multiple directories also. See the sample outputs:
Источник
Linux find exclude pattern
6. Find all the files except the ones under the temp directory. Also print the temp directories if present:
The only difference here is the print statement being present in the first half as well.
7. Find all the .c files except the ones present in the C directory:
The 1st part prunes out the C directories. In the second part, all the .c files are found and printed except the ones present in C.
8. Find all the .c files except the ones present in the C and temp directory:
To specify multiple directories with the -name option, -o should be used as an OR condition.
9. Find all files modified in the last one day except the ones present in the temp directory:
Usage of mtime makes find to search for files modified in the last day alone.
10. Find only regular files modified in the last one day except the ones present in the temp directory:
Using the -type f option, find will find only the regular files alone.
11. Find all files whose permission is 644 except the ones present in the temp directory:
-perm option in find allows to find files with specific permissions. permission 644 indicates files with permission rw-r—r—.
12. Same using the wholename option and prune to exclude directory:
13. Using exec and prune to exclude directory in-place of name:
One more way. Using the exec, a condition can be put to check whether the current file is «temp». If so, prune it. ‘<>‘ is the file found by the find command.
14. Using inum and prune to exclude directory in-place of name option:
Same, but using the inode number of the temp directory. inode number is specified using the inum option.
15. Find the list of all .c files except the ones present in the C directory without using prune:
-path option is like the -wholename option. It is used to specify a specific path to search. In this case, ‘! -path » tells to exclude this path alone. Since the specific path has been excluded in this way, the prune is not needed at all.
Источник
Команда 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 может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.
Источник