Linux find without directory

Команда find в Linux

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

Кроме того, с найденными файлами можно сразу же выполнять необходимые действия. В этой статье мы поговорим о поиске с помощью очень мощной команды find Linux, подробно разберем её синтаксис, опции и рассмотрим несколько примеров.

Основная информация о Find

Команда find — это одна из наиболее важных и часто используемых утилит системы Linux. Это команда для поиска файлов и каталогов на основе специальных условий. Ее можно использовать в различных обстоятельствах, например, для поиска файлов по разрешениям, владельцам, группам, типу, размеру и другим подобным критериям.

Утилита find предустановлена по умолчанию во всех Linux дистрибутивах, поэтому вам не нужно будет устанавливать никаких дополнительных пакетов. Это очень важная находка для тех, кто хочет использовать командную строку наиболее эффективно.

Команда find имеет такой синтаксис:

find [ папка] [ параметры] критерий шаблон [действие]

Папка — каталог в котором будем искать

Параметры — дополнительные параметры, например, глубина поиска, и т д

Критерий — по какому критерию будем искать: имя, дата создания, права, владелец и т д.

Шаблон — непосредственно значение по которому будем отбирать файлы.

Основные параметры команды find

Я не буду перечислять здесь все параметры, рассмотрим только самые полезные.

  • -P — никогда не открывать символические ссылки.
  • -L — получает информацию о файлах по символическим ссылкам. Важно для дальнейшей обработки, чтобы обрабатывалась не ссылка, а сам файл.
  • -maxdepth — максимальная глубина поиска по подкаталогам, для поиска только в текущем каталоге установите 1.
  • -depth — искать сначала в текущем каталоге, а потом в подкаталогах.
  • -mount искать файлы только в этой файловой системе.
  • -version — показать версию утилиты find.
  • -print — выводить полные имена файлов.
  • -type f — искать только файлы.
  • -type d — поиск папки в Linux.

Критерии

Критериев у команды find в Linux очень много, и мы опять же рассмотрим только основные.

  • -name — поиск файлов по имени.
  • -perm — поиск файлов в Linux по режиму доступа.
  • -user — поиск файлов по владельцу.
  • -group — поиск по группе.
  • -mtime — поиск по времени модификации файла.
  • -atime — поиск файлов по дате последнего чтения.
  • -nogroup — поиск файлов, не принадлежащих ни одной группе.
  • -nouser — поиск файлов без владельцев.
  • -newer — найти файлы новее чем указанный.
  • -size — поиск файлов в Linux по их размеру.
Читайте также:  Чем анализировать логи linux

Примеры использования

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

1. Поиск всех файлов

Показать все файлы в текущей директории:

Все три команды покажут одинаковый результат. Точка здесь означает текущую папку. Вместо неё можно указать любую другую.

2. Поиск файлов в определенной папке

Показать все файлы в указанной директории:

Искать файлы по имени в текущей папке:

Поиск по имени в текущей папке:

Не учитывать регистр при поиске по имени:

3. Ограничение глубины поиска

Поиска файлов по имени в Linux только в этой папке:

find . -maxdepth 1 -name «*.php»

4. Инвертирование шаблона

Найти файлы, которые не соответствуют шаблону:

5. Несколько критериев

Поиск командой find в Linux по нескольким критериям, с оператором исключения:

find . -name «test» -not -name «*.php»

Найдет все файлы, начинающиеся на test, но без расширения php. А теперь рассмотрим оператор ИЛИ:

find -name «*.html» -o -name «*.php»

Эта команда найдёт как php, так и html файлы.

6. Тип файла

По умолчанию find ищет как каталоги, так и файлы. Если вам необходимо найти только каталоги используйте критерий type с параметром d. Например:

find . -type d -name «Загрузки»

Для поиска только файлов необходимо использовать параметр f:

find . -type f -name «Загрузки»

6. Несколько каталогов

Искать в двух каталогах одновременно:

find ./test ./test2 -type f -name «*.c»

7. Поиск скрытых файлов

Найти скрытые файлы только в текущей папке. Имена скрытых файлов в Linux начинаются с точки:

find . -maxdepth 1 -type f -name «.*»

8. Поиск по разрешениям

Найти файлы с определенной маской прав, например, 0664:

Права также можно задавать буквами для u (user) g (group) и o (other). Например, для того чтобы найти все файлы с установленным флагом Suid в каталоге /usr выполните:

sudo find /usr -type f -perm /u=s

Поиск файлов доступных владельцу только для чтения только в каталоге /etc:

find /etc -maxdepth 1 -perm /u=r

Найти только исполняемые файлы:

find /bin -maxdepth 2 -perm /a=x

9. Поиск файлов в группах и пользователях

Найти все файлы, принадлежащие пользователю:

Поиск файлов в Linux принадлежащих группе:

find /var/www -group www-data

10. Поиск по дате модификации

Поиск файлов по дате в Linux осуществляется с помощью параметра mtime. Найти все файлы модифицированные 50 дней назад:

Поиск файлов в Linux открытых N дней назад:

Найти все файлы, модифицированные между 50 и 100 дней назад:

Найти файлы измененные в течении часа:

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

Найти все файлы размером 50 мегабайт:

От пятидесяти до ста мегабайт:

Найти самые маленькие файлы:

find . -type f -exec ls -s <> \; | sort -n -r | head -5

find . -type f -exec ls -s <> \; | sort -n | head -5

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

13. Действия с найденными файлами

Для выполнения произвольных команд для найденных файлов используется опция -exec. Например, для того чтобы найти все пустые папки и файлы, а затем выполнить ls для получения подробной информации о каждом файле используйте:

Удалить все текстовые файлы в tmp

find /tmp -type f -name «*.txt» -exec rm -f <> \;

Удалить все файлы больше 100 мегабайт:

find /home/bob/dir -type f -name *.log -size +100M -exec rm -f <> \;

Выводы

Вот и подошла к концу эта небольшая статья, в которой была рассмотрена команда find. Как видите, это одна из наиболее важных команд терминала Linux, позволяющая очень легко получить список нужных файлов. Ее желательно знать всем системным администраторам. Если вам нужно искать именно по содержимому файлов, то лучше использовать команду grep.

Читайте также:  Добавить java в path linux

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Use GNU find to show only the leaf directories

I’m trying to use GNU find to find only the directories that contain no other directories, but may or may not contain regular files. My best guess so far has been:

find dir -type d \( -not -exec ls -dA ';' \) 

When using -exec, the <> argument is expanded to the path of the currently inspected filesystem object (file / directory / . ). So you should have used the following command to print the directories : find dir -type d \( -not -exec ls -dA <> \; \)

Since this question ranks highly in search, see stackoverflow.com/a/9418016/315024 which gives the simplest answer: find -type d -empty

9 Answers 9

You can use -links if your filesystem is POSIX compliant (i.e. a directory has a link for each subdirectory in it, a link from its parent and a link to itself, thus a count of 2 links if it has no subdirectories).

The following command should do what you want:

However, it does not seems to work on Mac OS X (as @Piotr mentioned). Here is another version that is slower, but does work on Mac OS X. It is based on his version, with a correction to handle whitespace in directory names:

find . -type d -exec sh -c '(ls -p "<>"|grep />/dev/null)||echo "<>"' \; 

Similarly, the simple soln doesn’t seem to work in Cygwin (windows 7), but the extended OSx version does

The replacement string <> should be single-quoted to sh -c , not double quoted, since filenames might contain characters treated specially under double quotes (such as $ ).

I just found another solution to this that works on both Linux & macOS (without find -exec )!

It involves sort (twice) and awk :

find dir -type d | sort -r | awk 'a!~"^"$0' | sort 

Explanation:

  1. sort the find output in reverse order
    • now you have subdirectories appear first, then their parents
  2. use awk to omit lines if the current line is a prefix of the previous line
    • (this command is from the answer here)
    • now you eliminated «all parent directories» (you’re left with parent dirs)
  3. sort them (so it looks like the normal find output)
  4. Voila! Fast and portable.

The only problem with this ingenious/portable answer is that, as pointed out here it will fail if any character in the folder name is a regex special character. I’ve made a small modification and posted my answer here.

This will not work if one directory starts with a substring of another. For example, if one leaf directory is called «foo», and another «foobar», this will only show «foobar».

for that matter you can use sed to append a ‘/’ to the end of each line before awk and then remove them after awk

@Sylvian solution didn’t work for me on mac os x for some obscure reason. So I’ve came up with a bit more direct solution. Hope this will help someone:

find . -type d -print0 | xargs -0 -IXXX sh -c '(ls -p XXX | grep / >/dev/null) || echo XXX' ; 
  • ls -p ends directories with ‘/’
  • so (ls -p XXX | grep / >/dev/null) returns 0 if there is no directories
  • -print0 && -0 is to make xargs handle spaces in directory names
Читайте также:  Удалить всех пользователей линукс

Confused. find -print0 and xargs -0 are also not available out of the box on MacOS; but of course, you can avoid them both with find -exec , like Sylvain’s updated answer demonstrates.

I liked this solution. Seems very readable and a great alternative for cases when the links 2 approach does not work. I did need to double quote the XXX s though.

I have some oddly named files in my directory trees that confuse awk as in @AhmetAlpBalkan ‘s answer. So I took a slightly different approach

 p=; while read c; do l=$; f=$; if [ "$f" != "$c" ]; then echo $c; fi; p=$c; done < <(find . -type d | sort -r) 

As in the awk solution, I reverse sort. That way if the directory path is a subpath of the previous hit, you can easily discern this.

Here p is my previous match, c is the current match, l is the length of the current match, f is the first l matching characters of the previous match. I only echo those hits that don't match the beginning of the previous match.

The problem with the awk solution offered is that the matching of the beginning of the string seems to be confused if the path name contains things such as + in the name of some of the subdirectories. This caused awk to return a number of false positives for me.

Источник

How can I find a file/directory that could be anywhere on linux command line? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.

find [file or directory name] 

to report the paths with matching filenames/directories. Unfortunately this seems to only check the current directory, not the entire folder. I've also tried locate and which, but none find the file, even though I know its on the computer somewhere.

Not sure what the issue is, as find -name "filename" finds files recursively in the current working directory.

Sorry if it's not clear, the file may not be in the current working directory. It could be anywhere on the computer

5 Answers 5

"Unfortunately this seems to only check the current directory, not the entire folder". Presumably you mean it doesn't look in subdirectories. To fix this, use find -name "filename"

If the file in question is not in the current working directory, you can search your entire machine via

This also works with stuff like find / -name "*.pdf" , etc. Sometimes I like to pipe that into a grep statement as well (since, on my machine at least, it highlights the results), so I end up with something like

find / -name "*star*wars*" | grep star 

Doing this or a similar method just helps me instantly find the filename and recognize if it is in fact the file I am looking for.

Источник

Оцените статью
Adblock
detector