- Поиск текста в файлах Linux
- Что такое grep?
- Синтаксис grep
- Опции
- Примеры использования
- Поиск текста в файлах
- Вывести несколько строк
- Регулярные выражения в grep
- Рекурсивное использование grep
- Поиск слов в grep
- Поиск двух слов
- Количество вхождений строки
- Инвертированный поиск в grep
- Вывод имени файла
- Цветной вывод в grep
- Выводы
- How to Grep for Text in Files
- Using Grep
- The Grep Command
- Piping Command Outputs to grep
- Regular Expression Overview
- Filtering Logs with Grep
- Filtering Commands with Grep
- Excluding Patterns with grep
- Excluding grep When Using ps
- Grep Compressed Files with zgrep
- More Information
Поиск текста в файлах 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. При правильном применении эта утилита станет мощным инструментом в ваших руках. Если у вас остались вопросы, пишите в комментариях!
Источник
How to Grep for Text in Files
Grep is a command-line utility that can search and filter text using a common regular expression syntax. It is so ubiquitous that the verb “to grep” has emerged as a synonym for “to search.” grep is a useful tool for finding all occurrences of a search term in a selection of files, filtering a log file or stream, or as part of a script or chain of commands.
This guide provides an overview of grep usage, a brief introduction to regular expression syntax, and practical examples.
Using Grep
This guide references recent versions of GNU grep, which are included by default in all images provided by Linode. It is also provided as part of the common base selection of packages provided in nearly all distributions of Linux-based operating systems.
The Grep Command
A basic grep command uses the following syntax:
The first argument to grep is a search pattern. The second (optional) argument is the name of a file to be searched. The above sequence will search for all occurrences of “string” in the
If you want to search multiple files, the -r flag enables recursive searching through a directory tree:
When used on a specific file, grep only outputs the lines that contain the matching string. When run in recursive mode, grep outputs the full path to the file, followed by a colon, and the contents of the line that matches the pattern. Patterns in grep are, by default, basic regular expressions. If you need a more expressive regular expression syntax, grep is capable of accepting patterns in alternate formats with the following flags:
Flag | Usage |
---|---|
-E | Use extended regular expression syntax. Equivalent to the deprecated egrep command. |
-P | Use Perl regular expression syntax. |
Grep provides a number of powerful options to control its output:
Flag | Usage |
---|---|
-o | Output only the matching segment of each line, rather than the full contents of each matched line. |
-i | Ignore case distinctions, so that characters that differ only in case match each other. |
-n | Print the line number of each matched line. |
-C 2 | Show 2 (or another number of) context lines in addition to the matched line. |
-v | Invert the sense of matching, to select non-matching lines. |
-e | Specify a pattern. If this option is used multiple times, search for all patterns given. This option can be used to protect a pattern beginning with “-”. |
Piping Command Outputs to grep
In addition to reading content from files, grep can read and filter text from standard input. The output of any command or stream can be piped to the grep command. Then, grep filters this output according to the match pattern specified and outputs only the matching lines. For instance, given the following command:
This filters the output of the ls command’s help text and looks for appearances of “dired”, and outputs them to standard out:
Regular Expression Overview
While straightforward pattern matching is sufficient for some filtering tasks, the true power of grep lies in its ability to use regular expressions for complex pattern matching. Most characters in regular expressions match with input data literally; however, there are some sequences that carry special significance:
Symbol | Result |
---|---|
. | Matches any character. |
* | Matches zero or more instances of the preceding character. |
+ | Matches one or more instances of the preceding character. |
[] | Matches any of the characters within the brackets. |
() | Creates a sub-expression that can be combined to make more complicated expressions. |
|\ | OR operator; (www|ftp) matches either “www” or “ftp”. |
^ | Matches the beginning of a line. |
$ | Matches the end of the line. |
\ | Escapes the following character. Since . matches any character, to match a literal period you would need to use \. . |
Filtering Logs with Grep
One popular use of grep is to extract useful information from system logs:
In this command, grep filters an Apache access log for all lines that begin with an IP address, followed by a number of characters, a space and then the characters 200 (where 200 represents a successful HTTP connection). The -c option outputs only a count of the number of matches. To get the output of the IP address of the visitor and the path of the requested file for successful requests, omit the -c flag:
The curly brackets specify the number of instances of the pattern. <1,3>requires that the previous character occur at least once, but no more than three times. The character class 4 will match against one or more numeric digits. You can also generate similar output but report on unsuccessful attempts to access content:
The following command generates a list of all IP addresses that have attempted to connect to your web server. Using the -o option, only the matching strings are sent to standard output. This output is filtered through the utility uniq with the pipe operator ( | ) to filter out duplicate entries:
The next example uses an alternative pattern for matching an IP address in a different log. The following command searches the most recent /var/log/auth.log file for invalid login attempts:
You can split the above command into two layers to output a list of IP addresses with failed login attempts to your system:
grep can filter the output of commands such as tail -F to provide real-time monitoring of specific log events:
In this case, tail follows the
/procmail/procmail.log file. This output is passed to grep , which filters the stream and prints only lines that contain the string “Subject”.
Filtering Commands with Grep
grep can be used to filter long help files. This command filters the tar help text to more efficiently find the options for dealing with bzip files:
grep is also useful for filtering the output of ls when listing the contents of directories with a large number of files:
Excluding Patterns with grep
Rather than using grep to return matches for a search pattern, you can use grep to return non-matching lines by using the -v flag to perform an invert search. For example, the following command only returns lines that do not contain the pattern “string”:
You can also exclude multiple search patterns using invert search with grep -v by using the -e flag before each pattern as follows:
When you run the above command, it outputs all lines that do not contain “string” or “yarn”.
Excluding grep When Using ps
A useful application of invert searching is to exclude “grep” itself from a grep output, such as when using the ps command. For example, use the following command to search for all current processes that contain the pattern “log”:
Notice the last line of the output contains grep log , which is not relevant to the purpose of the search. You can exclude this line by using a pipe operator | and adding grep -v grep after it as follows:
While using grep -v grep not only excludes the grep log line, it also skips all other lines that contain “grep”, which may not be ideal. Luckily, there are other ways to remove grep from your output.
Instead, you can modify the grep log command and add a character class match to specifically match the first character l from log. This works because the excluded line contains grep [l]og , while only matches for “log” are returned. Run the command below to do a character class match for l as a character:
Alternatively, you can use the pgrep command instead of grep to search your current processes:
Grep Compressed Files with zgrep
zgrep command functions identically to the grep command above; however, it adds the ability to run grep operations on files that have been compressed with gzip without requiring an extra compression and decompression step. To search an older compressed log:
zgrep operations take longer than standard grep operations because of the additional overhead of reading the compressed files.
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on Wednesday, June 30, 2010.
Источник