Find all php linux

Содержание
  1. Команда find в Linux – мощный инструмент сисадмина
  2. Поиск по имени
  3. Поиск по типу файла
  4. Поиск по размеру файла
  5. Единицы измерения файлов:
  6. Поиск пустых файлов и каталогов
  7. Поиск времени изменения
  8. Поиск по времени доступа
  9. Поиск по имени пользователя
  10. Поиск по набору разрешений
  11. Операторы
  12. Действия
  13. -delete
  14. Заключение
  15. 35 Practical Examples of Linux Find Command
  16. 1. Find Files Using Name in Current Directory
  17. 2. Find Files Under Home Directory
  18. 3. Find Files Using Name and Ignoring Case
  19. 4. Find Directories Using Name
  20. 5. Find PHP Files Using Name
  21. 6. Find all PHP Files in the Directory
  22. 7. Find Files With 777 Permissions
  23. 8. Find Files Without 777 Permissions
  24. 9. Find SGID Files with 644 Permissions
  25. 10. Find Sticky Bit Files with 551 Permissions
  26. 11. Find SUID Files
  27. 12. Find SGID Files
  28. 13. Find Read-Only Files
  29. 14. Find Executable Files
  30. 15. Find Files with 777 Permissions and Chmod to 644
  31. 16. Find Directories with 777 Permissions and Chmod to 755
  32. 17. Find and remove single File
  33. 18. Find and remove Multiple File
  34. 19. Find all Empty Files
  35. 20. Find all Empty Directories
  36. 21. File all Hidden Files
  37. 22. Find Single File Based on User
  38. 23. Find all Files Based on User
  39. 24. Find all Files Based on Group
  40. 25. Find Particular Files of User
  41. 26. Find Last 50 Days Modified Files
  42. 27. Find Last 50 Days Accessed Files
  43. 28. Find Last 50-100 Days Modified Files
  44. 29. Find Changed Files in Last 1 Hour
  45. 30. Find Modified Files in Last 1 Hour
  46. 31. Find Accessed Files in Last 1 Hour
  47. 32. Find 50MB Files
  48. 33. Find Size between 50MB – 100MB
  49. 34. Find and Delete 100MB Files
  50. 35. Find Specific Files and Delete
  51. If You Appreciate What We Do Here On TecMint, You Should Consider:
  52. 25 simple examples of Linux find command
  53. Linux find command
  54. 1. List all files in current and sub directories
  55. 2. Search specific directory or path
  56. 3. Limit depth of directory traversal
  57. 4. Invert match
  58. 5. Combine multiple search criterias
  59. 6. Search only files or only directories
  60. 7. Search multiple directories together
  61. 8. Find hidden files
  62. 9. Find files with certain permissions
  63. 10. Find files with sgid/suid bits set
  64. 11. Find readonly files
  65. 12. Find executable files
  66. 13. Find files owned to particular user
  67. 14. Search files belonging to group
  68. Search file and directories based on modification date and time
  69. 15. Find files modified N days back
  70. 16. Find files accessed in last N days
  71. 17. Find files modified in a range of days
  72. 18. Find files changed in last N minutes.
  73. 19. Files modified in last hour
  74. 20. Find Accessed Files in Last 1 Hour
  75. 21. Find files of given size
  76. 22. Find files in a size range
  77. 23. Find largest and smallest files
  78. 24. Find empty files and directories
  79. Some advanced operations
  80. 25. List out the found files
  81. 26. Delete all matching files or directories
  82. Summary
  83. 55 thoughts on “ 25 simple examples of Linux find command ”

Команда 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
  • <> – является результатами поиска.
  • \; — Команда заканчивается точкой с запятой после обратного слеша.
Читайте также:  Xiaomi не устанавливается windows 10

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

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

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

Заключение

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

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

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

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

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

Источник

35 Practical Examples of Linux Find Command

The Linux find command is one of the most important and frequently used command command-line utility in Unix-like operating systems. The find command is used to search and locate the list of files and directories based on conditions you specify for files that match the arguments.

find command can be used in a variety of conditions like you can find files by permissions, users, groups, file types, date, size, and other possible criteria.

Through this article, we are sharing our day-to-day Linux find command experience and its usage in the form of examples.

In this article, we will show you the most used 35 Find Commands Examples in Linux. We have divided the section into Five parts from basic to advance usage of the find command.

  • Part I: Basic Find Commands for Finding Files with Names
  • Part II: Find Files Based on their Permissions
  • Part III: Search Files Based On Owners and Groups
  • Part IV: Find Files and Directories Based on Date and Time
  • Part V: Find Files and Directories Based on Size
  • Part VI: Find Multiple Filenames in Linux

1. Find Files Using Name in Current Directory

Find all the files whose name is tecmint.txt in a current working directory.

2. Find Files Under Home Directory

Find all the files under /home directory with the name tecmint.txt.

3. Find Files Using Name and Ignoring Case

Find all the files whose name is tecmint.txt and contains both capital and small letters in /home directory.

4. Find Directories Using Name

Find all directories whose name is Tecmint in / directory.

5. Find PHP Files Using Name

Find all php files whose name is tecmint.php in a current working directory.

6. Find all PHP Files in the Directory

Find all php files in a directory.

7. Find Files With 777 Permissions

Find all the files whose permissions are 777.

8. Find Files Without 777 Permissions

Find all the files without permission 777.

9. Find SGID Files with 644 Permissions

Find all the SGID bit files whose permissions are set to 644.

10. Find Sticky Bit Files with 551 Permissions

Find all the Sticky Bit set files whose permission is 551.

11. Find SUID Files

Find all SUID set files.

12. Find SGID Files

Find all SGID set files.

13. Find Read-Only Files

Find all Read-Only files.

14. Find Executable Files

Find all Executable files.

15. Find Files with 777 Permissions and Chmod to 644

Find all 777 permission files and use the chmod command to set permissions to 644.

16. Find Directories with 777 Permissions and Chmod to 755

Find all 777 permission directories and use the chmod command to set permissions to 755.

17. Find and remove single File

To find a single file called tecmint.txt and remove it.

18. Find and remove Multiple File

To find and remove multiple files such as .mp3 or .txt, then use.

19. Find all Empty Files

To find all empty files under a certain path.

20. Find all Empty Directories

To file all empty directories under a certain path.

21. File all Hidden Files

To find all hidden files, use the below command.

22. Find Single File Based on User

To find all or single files called tecmint.txt under / root directory of owner root.

23. Find all Files Based on User

To find all files that belong to user Tecmint under /home directory.

24. Find all Files Based on Group

To find all files that belong to the group Developer under /home directory.

25. Find Particular Files of User

To find all .txt files of user Tecmint under /home directory.

26. Find Last 50 Days Modified Files

To find all the files which are modified 50 days back.

27. Find Last 50 Days Accessed Files

To find all the files which are accessed 50 days back.

28. Find Last 50-100 Days Modified Files

To find all the files which are modified more than 50 days back and less than 100 days.

29. Find Changed Files in Last 1 Hour

To find all the files which are changed in the last 1 hour.

30. Find Modified Files in Last 1 Hour

To find all the files which are modified in the last 1 hour.

31. Find Accessed Files in Last 1 Hour

To find all the files which are accessed in the last 1 hour.

32. Find 50MB Files

To find all 50MB files, use.

33. Find Size between 50MB – 100MB

To find all the files which are greater than 50MB and less than 100MB.

34. Find and Delete 100MB Files

To find all 100MB files and delete them using one single command.

35. Find Specific Files and Delete

Find all .mp3 files with more than 10MB and delete them using one single command.

That’s it, We are ending this post here, In our next article, we will discuss more other Linux commands in-depth with practical examples. Let us know your opinions on this article using our comment section.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

25 simple examples of Linux find command

Linux find command

The Linux find command is a very useful and handy command to search for files from the command line. It can be used to find files based on various search criterias like permissions, user ownership, modification date/time, size etc. In this post we shall learn to use the find command along with various options that it supports.

The find command is available on most linux distros by default so you do not have to install any package. The find command is an essential one to learn, if you want to get super productive with the command line on linux.

The basic syntax of the find command looks like this

1. List all files in current and sub directories

This command lists out all the files in the current directory as well as the subdirectories in the current directory.

Читайте также:  Звуковые параметры для windows

The command is same as the following

2. Search specific directory or path

The following command will look for files in the test directory in the current directory. Lists out all files by default.

The following command searches for files by their name.

We can also use wildcards

Note that all sub directories are searched recursively. So this is a very powerful way to find all files of a given extension.

Trying to search the «/» directory which is the root, would search the entire file system including mounted devices and network storage devices. So be careful. Of course you can press Ctrl + c anytime to stop the command.

Ignore the case

It is often useful to ignore the case when searching for file names. To ignore the case, just use the «iname» option instead of the «name» option.

3. Limit depth of directory traversal

The find command by default travels down the entire directory tree recursively, which is time and resource consuming. However the depth of directory travesal can be specified. For example we don’t want to go more than 2 or 3 levels down in the sub directories. This is done using the maxdepth option.

The second example uses maxdepth of 1, which means it will not go lower than 1 level deep, either only in the current directory.

This is very useful when we want to do a limited search only in the current directory or max 1 level deep sub directories and not the entire directory tree which would take more time.

Just like maxdepth there is an option called mindepth which does what the name suggests, that is, it will go atleast N level deep before searching for the files.

4. Invert match

It is also possible to search for files that do no match a given name or pattern. This is helpful when we know which files to exclude from the search.

So in the above example we found all files that do not have the extension of php, either non-php files. The find command also supports the exclamation mark inplace of not.

5. Combine multiple search criterias

It is possible to use multiple criterias when specifying name and inverting. For example

The above find command looks for files that begin with abc in their names and do not have a php extension. This is an example of how powerful search expressions can be build with the find command.

When using multiple name criterias, the find command would combine them with AND operator, which means that only those files which satisfy all criterias will be matched. However if we need to perform an OR based matching then the find command has the «o» switch.

The above command search for files ending in either the php extension or the txt extension.

6. Search only files or only directories

Sometimes we want to find only files or only directories with a given name. Find can do this easily as well.

Quite useful and handy!

7. Search multiple directories together

So lets say you want to search inside 2 separate directories. Again, the command is very simple

Check, that it listed files from 2 separate directories.

8. Find hidden files

Hidden files on linux begin with a period. So its easy to mention that in the name criteria and list all hidden files.

9. Find files with certain permissions

The find command can be used to find files with a specific permission using the «perm» option. The following command searches for files with the permission 0664

This can be useful to find files with wrong permissions which can lead to security issues. Inversion can also be applied to permission checking.

10. Find files with sgid/suid bits set

The «perm» option of find command accepts the same mode string like chmod. The following command finds all files with permission 644 and sgid bit set.

Similarly use 1664 for sticky bit. The perm option also supports using an alternative syntax instead of octal numbers.

Note that the «2>/dev/null» removes those entries that have an error of «Permission Denied»

11. Find readonly files

Find all Read Only files.

12. Find executable files

The following command will find executable files

13. Find files owned to particular user

To find all or single file called tecmint.txt under /root directory of owner root.

We could also specify the name of the file or any name related criteria along with user criteria

Its very easy to see, how we can build up criteria after criteria to narrow down our search for matching files.

14. Search files belonging to group

Find all files that belong to a particular group.

Did you know you could search your home directory by using the

Search file and directories based on modification date and time

Another great search criteria that the find command supports is modification and accessed date/times. This is very handy when we want to find out which files were modified as a certain time or date range. Lets take a few examples

15. Find files modified N days back

To find all the files which are modified 50 days back.

16. Find files accessed in last N days

Find all files that were accessed in the last 50 days.

17. Find files modified in a range of days

Find all files that were modified between 50 to 100 days ago.

18. Find files changed in last N minutes.

Find files modified within the last 1 hour.

19. Files modified in last hour

To find all the files which are modified in last 1 hour.

20. Find Accessed Files in Last 1 Hour

To find all the files which are accessed in last 1 hour.

21. Find files of given size

Search files and directories based on size. To find all 50MB files, use.

22. Find files in a size range

To find all the files which are greater than 50MB and less than 100MB.

23. Find largest and smallest files

The find command when used in combination with the ls and sort command can be used to list out the largest files.
The following command will display the 5 largest file in the current directory and its subdirectory. This may take a while to execute depending on the total number of files the command has to process.

Similary when sorted in ascending order, it would show the smallest files first

24. Find empty files and directories

The following command uses the «empty» option of the find command, which finds all files that are empty.

To file all empty directories use the type «d».

Really very simple and easy

Some advanced operations

The find command not only finds files based on a certain criteria, it can also act upon those files using any linux command. For example, we might want to delete some files.

Here are some quick examples

25. List out the found files

Lets say we found files using find command, and now want to list them out as the ls command would have done. This is very easy.

26. Delete all matching files or directories

The following command will remove all text files in the tmp directory.

Читайте также:  Лучший mail клиент для windows

The same operating can be carried out with directories, just put type d, instead of type f.

Lets take another example where we want to delete files larger than 100MB

Summary

So that was a quick tutorial on the linux find command. The find command is one of the most essential commands on the linux terminal, that enables searching of files very easy. Its a must of all system administrators. So learn it up. Have any questions ? Leave a comment below.

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

55 thoughts on “ 25 simple examples of Linux find command ”

Great summary with categorized examples
Thanks!

Long Path tool can resolve error messages like: path too long, cannot delete file, too long path, destination path is too long, etc.

Very good article but how i can use find to search names with (S) for example ?

Becuase i try :
find . -iname ‘(S)’
find . -iname “(S)”

but the no results

Have you tried:
find . -iname ‘*(S)*’
or
find . -iname “*(S)*”
?

I wanna find a certain txt doc. in ROOT by using:
find / -name test.txt
Why does this command not work?

use this command instead (find ./filename)

Was after a solid search and replace technique for file names today, and uncovered this page on ‘find’. Thanks for the tips. I am sure I’ll incorporate them into day-to-day operations.

Hi everyone. I am Kreg i am from Philipines. Thanks for approved.

Thanks for the article. It’s really useful. I am wondering how can I use the find command and exclude the files that are using by some processes? I can find if files are used by process by:
find path_to_files -type f -name “some_name” -exec fuser <> \;
The output will show if there are files used by any processes but how can I get output that will show only files that are currently not used by any process?

It would become more perfect if “Delete all files which are older than X time” in the last. This is a good article. Thanks for sharing.

Your article is very informative. it’s really helpful……

You use the word “criterias”. That’s a mistake. Criteria is already plural. The singular is criterion. Thanks for providing the info here.

Excelente presentacion. buenos ejemplos y muy practicos.
Saludos.

That was really helpful. Concise and clear article, thank you!

Very nice presentation. Thank you so much

Very useful find command explanation. Thanks

Yes you are right about it

In connection with -o need to mention use of escaped parentheses \(, \) to group the criteria

Note: one criterion, two criteria, no criterias.

Also “Its” is a possessive adjective. “it’s” is short for “it is”.

thanks a lot for very useful post =))

Very useful article! Thank you!

You are awesome! this is a treasure trove of helpful information!

I used to have similar problems too, but after using”long path tool” everything was solved.

Please use this software and solve your computer, copy, delete, long path files.

Thanks for these good examples.

The path you entered, is too long. Enter a shorter path
File Name could not be found. Check the spelling of the filename,
and verify that the file location is correct.

I used to have similar problems too, but after using
“long path tool” You can use to solve this problem.

The path you entered, is too long. Enter a shorter path
File Name could not be found. Check the spelling of the filename,
and verify that the file location is correct.

Do not worry if you want to remove the blocked files or too long path files from your system, here I suggest a smooth way. Use “Long path tool” software and keep yourself cool.

Great intro! Thanks!
I think I have found a typo, in the Section “Find readonly files”: instead of “-perm /u=r” (which means: at least user-readable — compare with the following section), it should be “-perm -u=r”. That is, according to the man, ‘/’ means “at least” and ‘-‘ means “exactly”. I admit though that the man daunted me before I saw this page.

every command i tried fails with “find: paths must precede expression”
why?

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

-s what it will do ??

what about braces “ < >” in that ?

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

find = find files
. = directory to start at
-type = only match regular files

-exec = when you find a matching file, run this command
<> = the matching file
\; = the end of the command

So when find matches find foo.txt, it runs:

What -s means depends on the ls command.

Sorry, had a typo, it should be:

So when find matches foo.txt, it runs:

-s it print the allocated size

Thank you very much. i FIND it very helpful 🙂
Could you also please post some info regarding finding all files that contains a particular search text.

Isn’t command 25 deleting everyting larger than 10M, not 100M like in the description?

Thanks a lot. Clear and complete !

Very good. Thank you.

Awesome article . Great work

Rakesh, when you use <> ; with an exec statement the find utility will replace <> with the path and filename. In essence in the the example above if the following were the results without an exec command:

$ find /home/bob/dir -type f -name *.log -size +10M
/home/bob/dir/large.log
/home/bob/dir/even_larger.log

What find would do is run 2 separate statements:

$ find /home/bob/dir -type f -name *.log -size +10M -exec rm -f <> ;
rm -f /home/bob/dir/large.log
and
rm -f /home/bob/dir/even_larger.log

It is helpful to know that the path is relative, so if you were to say be in the /home/bob folder and use:
find . type f -name *.log -size +10M

Your results would end up like this:
./dir/large.log
./dir/even_larger.log

Very good briefing on FIND. perhaps AWK should be next? 🙂

I think you’ve got an mistake: Hidden files do NOT start with a period, they start with a dot. In your example you search in your home dir for hidden files.
The way to find executable files by usind find ist the “-executable” flag and you have to know that directories executeables, too.
If you just want to find executable files you can use

find PATH -executable -type f -name “whatever*”

on the other hand, if you looking for directories you can use

find PATH -executable -type d -name “whatever*”

what’s the difference between dot and period in the command line?

really helpfull, thank you very much

All the commands really useful…Thank you very much

thanks good article

Good examples, well explained.
But…
You need to quote all the wildcards in examples 2, 3, 4, 6, 7, 26.
Unless you’re going to explain to your readers why commands might fail unexpectly 🙂

Nice article, I bookmarked it for reference. It’d be interesting to have an offline version available for download, preferably as simple text, manpage or texinfo format.

Try using the backslash character before the parentheses, like “\(S\)”.

Источник

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