Find all files with text linux

Find Files Containing Specific Text in Linux

Linux, regardless of the distro you use, comes with a number of GUI tools which allow searching for files. Many modern file managers support file searching right in the file list. However, most of them do not allow you to search inside a file’s contents. Here are two methods you can use to search for file contents in Linux.

I would like to share the methods I use myself.
The first method involves the grep utility, which exists in any distro, even in embedded systems built on busybox.

To find files containing specific text in Linux, do the following.

  1. Open your favorite terminal app. XFCE4 terminal is my personal preference.
  2. Navigate (if required) to the folder in which you are going to search files with some specific text.
  3. Type the following command:

Here are the switches:
-i — ignore text case
-R — recursively search files in subdirectories.
-l — show file names instead of file contents portions.

./ — the last parameter is the path to the folder containing files you need to search for your text. In our case, it is the current folder with the file mask. You can change it to the full path of the folder. For example, here is my command

Note: Other useful switches you might want to use with grep:
-n — show the line number.
-w — match the whole word.

Another method I use is Midnight Commander (mc), the console file manager app. Unlike grep, mc is not included by default in all Linux distros I’ve tried. You may need to install it yourself.

Find files containing specific text with mc

To find files containing some specific text using Midnight Commander, start the app and press the following sequence on the keyboard:
Alt + Shift + ?
This will open the search dialog.

Fill in the «Content:» section and press the Enter key. It will find all files with the required text.

You can place these files in the left or right panel using the Panelize option and copy/move/delete/view/do whatever you want them.

Midnight Commander is a very time-saving tool when it comes to search.

Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:

Share this post

About Sergey Tkachenko

Sergey Tkachenko is a software developer from Russia who started Winaero back in 2011. On this blog, Sergey is writing about everything connected to Microsoft, Windows and popular software. Follow him on Telegram, Twitter, and YouTube.

6 thoughts on “ Find Files Containing Specific Text in Linux ”

The code that you provided helped me. There are also another commands which I cannot remember to find text in files but this one is made it quickly. I have bookmarked this post for further usage. Thank you.

WHAT ABOUT WINDOWS?!

I use Total Commander for that.

Midnight Commander reminds me of XTree for DOS way, evidently, way way, back in the day!! 🙂 Anyone else remember!?

It reminds me of Norton Commander. Good days.

Источник

How to find all files containing specific text on Linux

How to search a directory tree for all files containing specific text string on Linux using the command line. This tutorial will help you to search all files matching a string recursively. This tutorial uses “grep” command to search string in files. Alternatively, You can also also use the find command to search files with specific string.

Syntax

grep -rwl “search-string” /path/to/serch/dir

1. Search Single String in All Files

Below example command will search string “tecadmin” in all files in /var/log directory and its sub-directories.

2. Search Multiple String in All Files

You can also specify multiple strings to search using -e switch. This is similar to egrep command. Below example will search strings “tecadmin” and “https” in all files in /var/log directory and its sub-directories.

3. Search String in Specific Files

You can search string in files matching the file name criteria. Below example command will search string “tecadmin” in files ending with .log extension in /var/log directory and its sub-directories.

If you want to exclude some files matching file name criteria. You can exclude some files using –exclude option in command. For example, do not search file ending with .txt extension.

You can also exclude some directoires to skip search inside it. For example, do not search string files inside any folder having http in their name.

Frequently Uses Command Switches

Below is the frequently uses grep command switches. To list all switches details use grep —help command.

Источник

Команда 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 по их размеру

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

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

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

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

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

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

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

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

find . -iname «test*»

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

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

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

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

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

find . -not -name «test*»

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

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

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

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

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

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

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

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

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

Найти скрытые файлы:

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

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

find . type f -perm 0664

Найти файлы с установленным флагом suid/guid:

find / -perm 2644

find / -maxdepth 2 -perm /u=s

Поиск файлов только для чтения:

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

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

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

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

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

find . -user sergiy

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

find /var/www -group developer

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

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

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

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

find / -mtime +50 –mtime -100

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

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

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

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

find / -size +50M -size -100M

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

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

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

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

find /tmp -type f -empty

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

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

find . -exec ls -ld <> \;

Удалить все текстовые файлы в 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.

Источник

Find files containing a given text

In bash I want to return file name (and the path to the file) for every file of type .php|.html|.js containing the case-insensitive string «document.cookie» | «setcookie»

How would I do that?

6 Answers 6

The r flag means to search recursively (search subdirectories). The i flag means case insensitive.

If you just want file names add the l (lowercase L ) flag:

Try something like grep -r -n -i —include=»*.html *.php *.js» searchstrinhere .

the -i makes it case insensitlve

the . at the end means you want to start from your current directory, this could be substituted with any directory.

the -r means do this recursively, right down the directory tree

the -n prints the line number for matches.

the —include lets you add file names, extensions. Wildcards accepted

find them and grep for the string:

This will find all files of your 3 types in /starting/path and grep for the regular expression ‘(document\.cookie|setcookie)’ . Split over 2 lines with the backslash just for readability.

500Gb weigth directory.

Sounds like a perfect job for grep or perhaps ack

Or this wonderful construction:

Just to include one more alternative, you could also use this:

find «/starting/path» -type f -regextype posix-extended -regex «^.*\.(php|html|js)$» -exec grep -EH ‘(document\.cookie|setcookie)’ <> \;

  • -regextype posix-extended tells find what kind of regex to expect
  • -regex «^.*\.(php|html|js)$» tells find the regex itself filenames must match

-exec grep -EH ‘(document\.cookie|setcookie)’ <> \; tells find to run the command (with its options and arguments) specified between the -exec option and the \; for each file it finds, where <> represents where the file path goes in this command.

  • E option tells grep to use extended regex (to support the parentheses) and.
  • H option tells grep to print file paths before the matches.

And, given this, if you only want file paths, you may use:

find «/starting/path» -type f -regextype posix-extended -regex «^.*\.(php|html|js)$» -exec grep -EH ‘(document\.cookie|setcookie)’ <> \; | sed -r ‘s/(^.*):.*$/\1/’ | sort -u

  • | [pipe] send the output of find to the next command after this (which is sed , then sort )
  • r option tells sed to use extended regex.
  • s/HI/BYE/ tells sed to replace every First occurrence (per line) of «HI» with «BYE» and.
  • s/(^.*):.*$/\1/ tells it to replace the regex (^.*):.*$ (meaning a group [stuff enclosed by () ] including everything [ .* = one or more of any-character] from the beginning of the line [ ^ ] till’ the first ‘:’ followed by anything till’ the end of line [ $ ]) by the first group [ \1 ] of the replaced regex.
  • u tells sort to remove duplicate entries (take sort -u as optional).

. FAR from being the most elegant way. As I said, my intention is to increase the range of possibilities (and also to give more complete explanations on some tools you could use).

Источник

Читайте также:  Как перезагрузить компьютер через терминал линукс
Оцените статью