Find out terminal linux

Finding a directory in a Linux Terminal

How can I find a particular directory in a terminal window in Linux? I think it involves using grep, but I’m not sure how.

you have to provide at least some search criteria, «particular» is a bit vague. one can find items on the disc based upon names, relation ships, sizes, content, etc etc.

3 Answers 3

Would you be looking for something like this?

find . -type d | grep DIRNAME

Five years later I did notice the answer in the comment was slower to process than the original answer. Maybe a glitch. Anyone? Bueller?

If you want to find a particular directory that might be anywhere on your computer, the following will work, but it might take a while.

find / -name DIRNAME -type d 

And, if you want to find within the working directory — replace ‘ / ‘ with ‘ . ‘ — could get quicker.

If you have it installed, locate is designed for this. Google «man locate»

Though locate won’t provide you real-time results, but instead returns the results it gathered while updatedb was last run. If the filesystem doesn’t change much, then it isn’t a real problem and locate is very fast.

You must log in to answer this question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Команда find в Linux

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

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

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

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

Читайте также:  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 по их размеру.

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

А теперь давайте рассмотрим примеры 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 «.*»

Читайте также:  Linux как стереть файл

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.

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

Источник

How can I find a specific file from a Linux terminal?

I am trying to find where index.html is located on my linux server, and was wondering if there was a command to do that. Very new to linux and appreciate any help I can get.

Searching from / would take a few days to complete. And spit out a bunch of (non-critical) errors for certain types of files while searching. Not the most efficient.

Several years later, Googling «find file in linux» gives this as a top 10 result. I’m sure glad the question was asked and answered.

6 Answers 6

Find from root path find / -name «index.html»

Find from current path find . -name «index.html»

The below line of code would do it for you.

However, on most Linux servers, your files will be located in /var/www or in your user directory folder /home/(user) depending on how you have it set up. If you’re using a control panel, most likely it’ll be under your user folder.

Ah, liked stated below, the find program might take a while to complete. I’m not aware of any other option.

update db locate index.html 

Replace /var with your best guess as to the directory it is in but avoid starting from /

Читайте также:  Создать свою linux сборку

All other answers suggest using find (well, this answer also suggests using find but only after locate ), however, after several months of using find I realise locate is more convenient indeed! By the way, what is update db ? Do I need it?

@shintaroid locate does not actually search on your files system for a given file. What it does is it caches the information about the files into a database which is refreshed by a job on a given time interval. So what updatedb does is just to update the database manually.

Solution: Use unix command find

The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the ‘primaries’ and ‘operands’) in terms of each file in the tree.

  • You can make the find action be more efficient and smart by controlling it with regular expressions queries, file types, size thresholds, depths dimensions in subtree, groups, ownership, timestamps , modification/creation date and more.
  • In addition you can use operators and combine find requests such as or/not/and etc.

The Traditional Formula would be :

Easy Examples

1.Find by Name — Find all package.json from my current location subtree hierarchy.

2.Find by Name and Type — find all node_modules directories from ALL file system (starting from root hierarchy )

sudo find / -name "node_modules" -type d 

Complex Examples:

More Useful examples which can demonstrate the power of flag options and operators:

3.Regex and File Type — Find all javascript controllers variation names (using regex) javascript Files only in my app location.

find /user/dev/app -name "*contoller-*\.js" -type f 

-type f means file -name related to regular expression to any variation of controller string and dash with .js at the end

4.Depth — Find all routes patterns directories in app directory no more than 3 dimensions ( app/../../.. only and no more deeper)

find app -name "*route*" -type d -maxdepth 3 

-type d means directory -name related to regular expression to any variation of route string -maxdepth making the finder focusing on 3 subtree depth and no more /depth1/depth2/depth3 )

5.File Size , Ownership and OR Operator — Find all files with names ‘sample’ or ‘test’ under ownership of root user that greater than 1 Mega and less than 5 Mega.

find . \( -name "test" -or -name "sample" \) -user root -size +1M -size -5M 

-size threshold representing the range between more than (+) and less than (-) -user representing the file owner -or operator filters query for both regex matches

6.Empty Files — find all empty directories in file system

7.Time Access, Modification and creation of files — find all files that were created/modified/access in directory in 10 days

# creation (c) find /test -name "*.groovy" -ctime -10d # modification (m) find /test -name "*.java" -mtime -10d # access (a) find /test -name "*.js" -atime -10d 

8.Modification Size Filter — find all files that were modified exactly between a week ago to 3 weeks ago and less than 500kb and present their sizes as a list

find /test -name "*.java" -mtime -3w -mtime +1w -size -500k | xargs du -h 

Источник

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