- Linux find text in files
- Find text in files into a directory
- 1. Find text in files recursive
- 2. Find text in files case insensitive and recursive
- 3. Find multiple words in files
- Find Files Containing Specific Text in Linux
- Find files containing specific text with mc
- About Sergey Tkachenko
- 6 thoughts on “ Find Files Containing Specific Text in Linux ”
- Команда find в Linux – мощный инструмент сисадмина
- Поиск по имени
- Поиск по типу файла
- Поиск по размеру файла
- Единицы измерения файлов:
- Поиск пустых файлов и каталогов
- Поиск времени изменения
- Поиск по времени доступа
- Поиск по имени пользователя
- Поиск по набору разрешений
- Операторы
- Действия
- -delete
- Заключение
- Finding a File Containing a Particular Text String In Linux Server
- grep command syntax for finding a file containing a particular text string
- How to search and find all files for a given text string
- Task: Search all subdirectories recursively
- Task: Only display filenames
- Task: Suppress file names
- Task: Display only words
- Task: Search for two or more words
- Task: Hide warning spam
- Task: Display matched text in color
- Task: Ignore case
- How do I find all files containing specific text on Linux?
- Finding text strings within files using grep
Linux find text in files
Posted on February 12, 2016 By Nikola Stojanoski
If you need to find text in file or multiple files on a Linux system you can use grep (global regular expression print) in a very efficient way to do so. Here are few examples that I commonly use.
Find text in files into a directory
Use this command to find the text you are looking for within the directory
If you want to select only those lines containing matches that form whole words use the -w switch (–word-regexp). If you search for “word” this will NOT display words like someword, word123, etc.
If you don’t know the capitalization of words and want to ignore case distinctions use the -i switch (–ignore-case). If you search for “word” it will display Word, WORD, word, wORD, etc.
And the most often used command for me is recursive search -r switch (–recursive)
And finally few examples that i use the most
1. Find text in files recursive
Invoke -w (–word-regexp) and -r (–recursive) switch:
2. Find text in files case insensitive and recursive
Invoke -i (–ignore-case) and -r (–recursive) switch
3. Find multiple words in files
To find two different words you must use egrep
This days i use this to search trough logs, mostly apache, nginx and mail logs.
Also don’t forget to use zgrep. Zgrep invokes grep on compressed or gzipped files. All options specified are passed directly to grep.
For this we will use grep case insensitive because sometimes mail addresses can have Capital letters in the user First and Last Names.
This will output file and date when the mail was sent to the user, and than you can grep the time to get all the logs for that time:
You can now easy look at the log:
This ware just few command i usually use, look at the man page for more options.
Источник
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.
- Open your favorite terminal app. XFCE4 terminal is my personal preference.
- Navigate (if required) to the folder in which you are going to search files with some specific text.
- 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.
Источник
Команда 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 может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.
Источник
Finding a File Containing a Particular Text String In Linux Server
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | grep |
Est. reading time | Less than 2 minutes |
You need to use the grep command. The grep command or egrep command searches the given input FILEs for lines containing a match or a text string.
grep command syntax for finding a file containing a particular text string
The syntax is:
grep » text string to search » directory-path
grep [option] » text string to search » directory-path
grep -r » text string to search «directory-path
grep -r -H » text string to search » directory-path
egrep -R » word-1|word-2 » /path/to/directory
egrep -w -R » word-1|word-2 » directory-path
Let us see some common example on how to use grep to search for strings in files.
How to search and find all files for a given text string
In this example, search for a string called ‘redeem reward’ in all text (*.txt) files located in /home/tom/ directory, use:
$ grep «redeem reward» /home/tom/*.txt
OR
$ grep «redeem reward»
Task: Search all subdirectories recursively
You can search for a text string all files under each directory, recursively with -r option:
$ grep -r «redeem reward» /home/tom/
OR
$ grep -R «redeem reward» /home/tom/
Look for all files containing cacheRoot text on Linux:
grep -R cacheRoot /home/vivek/
Trying to find all files containing specific text on my Linux desktop
Task: Only display filenames
By default, the grep command prints the matching lines. You can pass -H option to print the filename for each match:
$ grep -H -r «redeem reward» /home/tom
Sample outputs:
To just display the filename use the cut command as follows:
$ grep -H -R vivek /etc/* | cut -d: -f1
Sample outputs:
Task: Suppress file names
The grep command shows output on a separate line, and it is preceded by the name of the file in which it was found in the case of multiple files. You can pass the -h option to suppress inclusion of the file names in the output:
$ grep -h -R ‘main()’
Task: Display only words
You can select only those lines containing matches that form whole words using the -w option. In this example, search for word ‘getMyData()’ only in
/projects/ dirctory:
$ grep -w -R ‘getMyData()’
Task: Search for two or more words
Use the egrep command as follows:
$ egrep -w -R ‘word1|word2’
- 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 ➔
Task: Hide warning spam
grep command generate error message as follows due to permission and other issues:
No such file or directory
No such device or address
Permission denied
To hide all errors or warning message spam generated by the grep command, append 2>/dev/null to grep command. This will send and hide unwanted output to /dev/null device:
$ grep -w -R ‘getMyData()’
Task: Display matched text in color
Pass the —color option to the grep command display matched text/words in color on the terminal:
Fig.01: grep command in action with colors and hiding the warnings on screen
Task: Ignore case
Our final example ignore case distinctions in both the search PATTERN and the input files:
grep -i -R ‘word’ /path/to/dir
grep -i -r ‘income tax’
How do I find all files containing specific text on Linux?
The syntax is:
egrep ‘pattern’ -rnw /path/to/dir/
egrep ‘word1|word2’ -rnw /home/vivek/backups/
Finding text strings within files using grep
In this example search for lines starting with any lowercase or uppercase letter:
grep «^[a-zA-Z]» -rns
- -r – Recursive search
- -R – Read all files under each directory, recursively. Follow all symbolic links, unlike -r grep option
- -n – Display line number of each matched line
- -s – Suppress error messages about nonexistent or unreadable files
- -w – Only work on words i.e. search only those lines containing matches that form whole words
- -l – Show the name of each input file when match found
- -i – Ignore case while searching
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник