How to Find a Specific String or Word in Files and Directories
Do you want to find all files that contain a particular word or string of text on your entire Linux system or a given directory. This article will guide you on how to do that, you will learn how to recursively dig through directories to find and list all files that contain a given string of text.
A simple way to work this out is by using grep pattern searching tool, is a powerful, efficient, reliable and most popular command-line utility for finding patterns and words from files or directories on Unix-like systems.
The command below will list all files containing a line with the text “check_root”, by recursively and aggressively searching the
Find a Word in Directory
Where the -R option tells grep to read all files under each directory, recursively, following symbolic links only if they are on the command line and option -w instructs it to select only those lines containing matches that form whole words, and -e is used to specify the string (pattern) to be searched.
You should use the sudo command when searching certain directories or files that require root permissions (unless you are managing your system with the root account).
To ignore case distinctions employ the -i option as shown:
If you want to know the exact line where the string of text exist, include the -n option.
Find String with Line Number
Assuming there are several types of files in a directory you wish to search in, you can also specify the type of files to be searched for instance, by their extension using the —include option.
This example instructs grep to only look through all .sh files.
In addition, it is possible to search for more than one pattern, using the following command.
Find Multiple Words in Files
That’s It! If you know any other command-line trick to find string or word in files, do share with us or ask any questions regarding this topic, use the comment form below.
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.
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 в 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. Поиск файлов в определенной папке
Показать все файлы в указанной директории:
Искать файлы по имени в текущей папке:
Не учитывать регистр при поиске по имени:
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 / -maxdepth 2 -perm /u=s
Поиск файлов только для чтения:
find /etc -maxdepth 1 -perm /u=r
Найти только исполняемые файлы:
find /bin -maxdepth 2 -perm /a=x
9. Поиск файлов по группах и пользователях
Найти все файлы, принадлежащие пользователю:
Поиск файлов в 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 для получения подробной информации о каждом файле:
Удалить все текстовые файлы в tmp
find /tmp -type f -name «*.txt» -exec rm -f <> \;
Удалить все файлы больше 100 мегабайт:
find /home/bob/dir -type f -name *.log -size +10M -exec rm -f <> \;
Выводы
Вот и подошла к концу эта небольшая статья, в которой была рассмотрена команда find. Как видите, это одна из наиболее важных команд терминала Linux, позволяющая очень легко получить список нужных файлов. Ее желательно знать всем системным администраторам. Если вам нужно искать именно по содержимому файлов, то лучше использовать команду grep.