Search all text files linux

Содержание
  1. Linux find text in files
  2. Find text in files into a directory
  3. 1. Find text in files recursive
  4. 2. Find text in files case insensitive and recursive
  5. 3. Find multiple words in files
  6. How to find all files containing specific text on Linux
  7. Syntax
  8. grep -rwl “search-string” /path/to/serch/dir
  9. 1. Search Single String in All Files
  10. 2. Search Multiple String in All Files
  11. 3. Search String in Specific Files
  12. 4. Exclude Some Files from Search
  13. 5. Exclude Some Directories from Search
  14. Frequently Uses Command Switches
  15. Linux / UNIX Recursively Search All Files For A String
  16. How to use grep command to recursively search All files for a String
  17. Following symtlinks
  18. Case sensitive recursive search
  19. Displaying files name when searching for a string/word
  20. Using find command to search recursively
  21. Finding all files containing specific text on Linux
  22. How to search only files that have specific extensions
  23. Understanding grep command options that used for searching text files
  24. Summing up
  25. Find Files Containing Specific Text in Linux
  26. Find files containing specific text with mc
  27. About Sergey Tkachenko
  28. 6 thoughts on “ Find Files Containing Specific Text in Linux ”
  29. Поиск текста в файлах Linux
  30. Что такое grep?
  31. Синтаксис grep
  32. Опции
  33. Примеры использования
  34. Поиск текста в файлах
  35. Вывести несколько строк
  36. Регулярные выражения в grep
  37. Рекурсивное использование grep
  38. Поиск слов в grep
  39. Поиск двух слов
  40. Количество вхождений строки
  41. Инвертированный поиск в grep
  42. Вывод имени файла
  43. Цветной вывод в grep
  44. Выводы

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.

Источник

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.

Читайте также:  Можно ли переустановить windows без флешки

Источник

Linux / UNIX Recursively Search All Files For A String

H ow do I recursively search all text files for a string such as foo under UNIX / Linux / *BSD / Mac OS X shell prompt?

You can use grep command or find command as follows to search all files for a string or words recursively.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux or Unix with grep and find utilities
Est. reading time 2 minutes

The syntax is as follows for the grep command to find all files under Linux or Unix in the current directory:
cd /path/to/dir
grep -r «word» .
grep -r «string» .
The -r option read/sarch all files under each directory, recursively, following symbolic links only if they are on the command line. In other words, it will look into sub-directories too. We can also state path as follows:
grep -r ‘something’ /path/to/dir

The following syntax will read and search all files under each directory, recursively. Follow all symbolic links too by passing the -R (capital R ):
grep -R ‘word’ .
grep -R ‘string-to-search’ /path/to/dir/

To ignore case distinctions, try:
grep -ri «word» .

Displaying files name when searching for a string/word

To display print only the filenames with GNU grep, enter:
grep -r -l «foo» .
You can also specify directory name:
grep -r -l «foo» /path/to/dir/*.c

Using find command to search recursively

find command is recommend because of speed and ability to deal with filenames that contain spaces.

  • 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

Older UNIX version should use xargs to speed up things:
find /path/to/dir -type f | xargs grep -l «foo»
It is good idea to pass -print0 option to find command that it can deal with filenames that contain spaces or other metacharacters:
find /path/to/dir -type f -print0 | xargs -0 grep -l «foo»
OR use the following OSX/BSD/find or GNU/find example:

Sample outputs from the last command:

Fig.01: Unix and Linux: How to Grep Recursively?

Finding all files containing specific text on Linux

Say you want to find orange and mango words, then try:
grep -r -E ‘orange|mango’ .
grep -r -E ‘orange|mango’ /dir/to/search/
This is how you set up pattern
grep -r -e ‘pattern’ /dir/to/search
For extended grep (see egrep command for regular expressions):
egrep -r ‘word’ /dir/to/search/
egrep -r ‘regex’ /dir/to/search/
We can combine all options too:
grep -rnw -e ‘pattern’ /dir/to/search/
egrep -rnw ‘regex’ /path/to/search/

How to search only files that have specific extensions

Want to search files having either ‘.pl’ or ‘.php’ extensions for foo() ? Try:
grep —include=\*. -rnw «foo()» /dir/to/search/
egrep —include=\*. -rnw «regex» /dir/to/search/
We can skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching. For instance, exclude all .bin files:
grep —exclude=\*.bin -r -n -0 ‘string_to_search’ /path/
egrep —exclude=\*.bin -r -n -0 ‘regex’ /path/to/search/
When searching recursively, we can skip any subdirectory whose base name matches wildcard. For instance, skip includes and docs directory:

Understanding grep command options that used for searching text files

  • -r : Rrecursive search
  • -i : Ignore case distinctions in patterns and data
  • -w : Match only whole words
  • -n : Show line number with output lines
  • -e ‘pattern’ : Use PATTERNS for matching
  • -E : All search PATTERNS are extended regular expressions
  • —include=GLOB : Search only files that match GLOB (a file pattern)
  • —exclude=GLOB : Skip files that match GLOB
  • —exclude-dir=GLOB : Skip directories that match GLOB

GLOB means to expand to wildcard patterns. For example, GLOB, *.txt means all files ending with .txt extension. A string is a wildcard pattern if it contains one of the following characters:

  1. ? – Matches any single character.
  2. * – Matches any string, including the empty string.
  3. [

Globbing is the operation that expands a wildcard pattern into the list of path-names matching the pattern.

Summing up

You learned how to search for text, string, or words recursively on Linux, macOS, *BSD, and Unix-like systems. See the following man pages:
man grep
man find
man 3 glob
man 7 glob

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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.

Источник

Поиск текста в файлах Linux

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

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

Что такое grep?

Команда grep (расшифровывается как global regular expression print) — одна из самых востребованных команд в терминале Linux, которая входит в состав проекта GNU. Секрет популярности — её мощь, она даёт возможность пользователям сортировать и фильтровать текст на основе сложных правил.

Утилита grep решает множество задач, в основном она используется для поиска строк, соответствующих строке в тексте или содержимому файлов. Также она может находить по шаблону или регулярным выражениям. Команда в считанные секунды найдёт файл с нужной строчкой, текст в файле или отфильтрует из вывода только пару нужных строк. А теперь давайте рассмотрим, как ей пользоваться.

Синтаксис grep

Синтаксис команды выглядит следующим образом:

$ grep [опции] шаблон [имя файла. ]

$ команда | grep [опции] шаблон

  • Опции — это дополнительные параметры, с помощью которых указываются различные настройки поиска и вывода, например количество строк или режим инверсии.
  • Шаблон — это любая строка или регулярное выражение, по которому будет вестись поиск
  • Файл и команда — это то место, где будет вестись поиск. Как вы увидите дальше, grep позволяет искать в нескольких файлах и даже в каталоге, используя рекурсивный режим.

Возможность фильтровать стандартный вывод пригодится,например, когда нужно выбрать только ошибки из логов или найти PID процесса в многочисленном отчёте утилиты ps.

Опции

Давайте рассмотрим самые основные опции утилиты, которые помогут более эффективно выполнять поиск текста в файлах grep:

  • -b — показывать номер блока перед строкой;
  • -c — подсчитать количество вхождений шаблона;
  • -h — не выводить имя файла в результатах поиска внутри файлов Linux;
  • -i — не учитывать регистр;
  • — l — отобразить только имена файлов, в которых найден шаблон;
  • -n — показывать номер строки в файле;
  • -s — не показывать сообщения об ошибках;
  • -v — инвертировать поиск, выдавать все строки кроме тех, что содержат шаблон;
  • -w — искать шаблон как слово, окружённое пробелами;
  • -e — использовать регулярные выражения при поиске;
  • -An — показать вхождение и n строк до него;
  • -Bn — показать вхождение и n строк после него;
  • -Cn — показать n строк до и после вхождения;

Все самые основные опции рассмотрели и даже больше, теперь перейдём к примерам работы команды grep Linux.

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

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

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

В первом примере мы будем искать пользователя User в файле паролей Linux. Чтобы выполнить поиск текста grep в файле /etc/passwd введите следующую команду:

grep User /etc/passwd

В результате вы получите что-то вроде этого, если, конечно, существует такой пользователь:

А теперь не будем учитывать регистр во время поиска. Тогда комбинации ABC, abc и Abc с точки зрения программы будут одинаковы:

grep -i «user» /etc/passwd

Вывести несколько строк

Например, мы хотим выбрать все ошибки из лог-файла, но знаем, что в следующей строчке после ошибки может содержаться полезная информация, тогда с помощью grep отобразим несколько строк. Ошибки будем искать в Xorg.log по шаблону «EE»:

grep -A4 «EE» /var/log/xorg.0.log

Выведет строку с вхождением и 4 строчки после неё:

grep -B4 «EE» /var/log/xorg.0.log

Выведет целевую строку и 4 строчки до неё:

grep -C2 «EE» /var/log/xorg.0.log

Выведет по две строки с верху и снизу от вхождения.

Регулярные выражения в grep

Регулярные выражения grep — очень мощный инструмент в разы расширяющий возможности поиска текста в файлах. Для активации этого режима используйте опцию -e. Рассмотрим несколько примеров:

Поиск вхождения в начале строки с помощью спецсимвола «^», например, выведем все сообщения за ноябрь:

grep «^Nov 10» messages.1

Nov 10 01:12:55 gs123 ntpd[2241]: time reset +0.177479 s
Nov 10 01:17:17 gs123 ntpd[2241]: synchronized to LOCAL(0), stratum 10

Поиск в конце строки — спецсимвол «$»:

grep «terminating.$» messages

Jul 12 17:01:09 cloneme kernel: Kernel log daemon terminating.
Oct 28 06:29:54 cloneme kernel: Kernel log daemon terminating.

Найдём все строки, которые содержат цифры:

grep «2» /var/log/Xorg.0.log

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

Рекурсивное использование grep

Если вам нужно провести поиск текста в нескольких файлах, размещённых в одном каталоге или подкаталогах, например в файлах конфигурации Apache — /etc/apache2/, используйте рекурсивный поиск. Для включения рекурсивного поиска в grep есть опция -r. Следующая команда займётся поиском текста в файлах Linux во всех подкаталогах /etc/apache2 на предмет вхождения строки mydomain.com:

grep -r «mydomain.com» /etc/apache2/

В выводе вы получите:

grep -r «zendsite» /etc/apache2/
/etc/apache2/vhosts.d/zendsite_vhost.conf: ServerName zendsite.localhost
/etc/apache2/vhosts.d/zendsite_vhost.conf: DocumentRoot /var/www/localhost/htdocs/zendsite
/etc/apache2/vhosts.d/zendsite_vhost.conf:

Здесь перед найденной строкой указано имя файла, в котором она была найдена. Вывод имени файла легко отключить с помощью опции -h:

grep -h -r «zendsite» /etc/apache2/

ServerName zendsite.localhost
DocumentRoot /var/www/localhost/htdocs/zendsite

Поиск слов в grep

Когда вы ищете строку abc, grep будет выводить также kbabc, abc123, aafrabc32 и тому подобные комбинации. Вы можете заставить утилиту искать по содержимому файлов в Linux только те строки, которые выключают искомые слова с помощью опции -w:

grep -w «abc» имя_файла

Поиск двух слов

Можно искать по содержимому файла не одно слово, а два сразу:

egrep -w ‘word1|word2’ /path/to/file

Количество вхождений строки

Утилита grep может сообщить, сколько раз определённая строка была найдена в каждом файле. Для этого используется опция -c (счетчик):

grep -c ‘word’ /path/to/file

C помощью опции -n можно выводить номер строки, в которой найдено вхождение, например:

grep -n ‘root’ /etc/passwd

Инвертированный поиск в grep

Команда grep Linux может быть использована для поиска строк в файле, которые не содержат указанное слово. Например, вывести только те строки, которые не содержат слово пар:

grep -v пар /path/to/file

Вывод имени файла

Вы можете указать grep выводить только имя файла, в котором было найдено заданное слово с помощью опции -l. Например, следующая команда выведет все имена файлов, при поиске по содержимому которых было обнаружено вхождение primary:

grep -l ‘primary’ *.c

Цветной вывод в grep

Также вы можете заставить программу выделять другим цветом вхождения в выводе:

grep —color root /etc/passwd

Выводы

Вот и всё. Мы рассмотрели использование команды grep для поиска и фильтрации вывода команд в операционной системе Linux. При правильном применении эта утилита станет мощным инструментом в ваших руках. Если у вас остались вопросы, пишите в комментариях!

Источник

Читайте также:  Тема для windows skins
Оцените статью