Linux find strings in files

Linux find strings in files

The commands used are mainly grep and find.

Find string in file

grep string filename

grep name file.txt

Find string in file ignoring cases

grep string filename

grep -i name file.txt

Find string in current directory

grep string .

Find string recursively

grep -r string .

Find files that do not contain a string

grep -L string .

Find string recursively in only some specific files

grep string -r . —include=*.myextension

grep string -r . —include=*.

grep «name=Oscar» -r . —include=*.js

* if you specify —include it won’t look for the string in all files, just the ones included

Find string recursively in all files except the ones that contain certain extensions

grep string -r . —exclude=*.

grep «Serializable» -rl . —exclude=*.

Find string recursively all files including some extensions and excluding others

grep string -r . —include=*.myextension —exclude=*.myextension2

grep «my=string» -r . —include=*. —exclude=*.js

*It won’t look for the string in the js files.

Find string recursively in only some specific files and show their filename

grep string -rl . —include=*.myextension

grep «name=Oscar» -rl . —include=*.js

Find files and find a string in them using find

find . -name ‘*.extension’ -exec grep string +

find . -name ‘*.txt’ -exec grep Mytext <> +

find . -type f \( -name ‘*.htm’ -or -name ‘*.html’ \) -exec grep -i «mystring» <> +

Источник

Last Updated: December 21st, 2019 by Hitesh J in Guides, Linux

When you are working on a server that has a big and large set of files, you must have a knowledge of grep command to search files that containing a specific string.

Find command is not capable to look inside a text file for a string.

Grep also know as a “global search for the regular expression” is a command-line utility that can be used to search for lines matching a specific string and display the matching lines to standard output.

In this tutorial, we will show you how to find files that contain specific string in Linux.

Basic Syntax of Grep to Find Strings/Text in Files/Directories

The basic syntax of grep command is shown below:

grep -irhnwl «search string» «directory-path»

Where:

  • -i : Used to ignore case sensitive string.
  • -r : Used to search directory recursively.
  • -h : Used to suppress the inclusion of the file names in the output.
  • -n : Used to display line numbers in the output.
  • -w : Used to search for matching whole words only.
  • -l : Used to display filename without matching string.

For more information about grep comamnd, run the following command:

You should see the grep manual page in the following screen:

To Search a File

To search all the lines that containing specific string in the single file use the following syntax:

grep «string» «path-of-the-file»

For example, search for a string called “nginx” in the file /etc/nginx/nginx.conf, run the following command:

grep nginx /etc/nginx/nginx.conf

Читайте также:  Скоро выйдет отличное приложение windows 10

You should see the following output:

pid /run/nginx.pid;
include /etc/nginx/mime.types;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# nginx-naxsi config
# Uncomment it if you installed nginx-naxsi
#include /etc/nginx/naxsi_core.rules;
# nginx-passenger config
# Uncomment it if you installed nginx-passenger
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript

To search for a string called “nginx” in all the files located inside directory /etc/nginx/, run the following command:

grep nginx /etc/nginx/*

You should see the following output:

grep: /etc/nginx/conf.d: Is a directory
/etc/nginx/fastcgi_params:fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
/etc/nginx/koi-utf:# If you need a full and standard map, use contrib/unicode2nginx/koi-utf
/etc/nginx/naxsi-ui.conf.1.4.1:rules_path = /etc/nginx/naxsi_core.rules
/etc/nginx/nginx.conf:pid /run/nginx.pid;
/etc/nginx/nginx.conf: include /etc/nginx/mime.types;
/etc/nginx/nginx.conf: access_log /var/log/nginx/access.log;
/etc/nginx/nginx.conf: error_log /var/log/nginx/error.log;
/etc/nginx/nginx.conf: # nginx-naxsi config
/etc/nginx/nginx.conf: # Uncomment it if you installed nginx-naxsi
/etc/nginx/nginx.conf: #include /etc/nginx/naxsi_core.rules;
/etc/nginx/nginx.conf: # nginx-passenger config
/etc/nginx/nginx.conf: # Uncomment it if you installed nginx-passenger
/etc/nginx/nginx.conf: include /etc/nginx/conf.d/*.conf;
/etc/nginx/nginx.conf: include /etc/nginx/sites-enabled/*;
/etc/nginx/nginx.conf:# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
grep: /etc/nginx/sites-available: Is a directory
grep: /etc/nginx/sites-enabled: Is a directory
/etc/nginx/win-utf:# use contrib/unicode2nginx/win-utf map instead.

Search All Files in a Specific Directory Recursively

To search for a specific string in all files located inside specific directory recursively, use the following syntax:

grep -r «search-string» «/path-of-the-directory»

For example, find all files that containing string called “ubuntu” in the directory /mnt/grub.d recursively, run the following command:

grep -r ubuntu /mnt/grub.d/

You should see the following output:

/mnt/grub.d/10_linux:ubuntu_recovery=»1″
/mnt/grub.d/10_linux: Ubuntu|Kubuntu)
/mnt/grub.d/10_linux:if [ «$ubuntu_recovery» = 1 ]; then
/mnt/grub.d/10_linux: if ([ «$ubuntu_recovery» = 0 ] || [ x$type != xrecovery ]) && \
/mnt/grub.d/05_debian_theme: Tanglu|Ubuntu|Kubuntu)
/mnt/grub.d/05_debian_theme: Ubuntu|Kubuntu)

In the above output, you should see all the search string with the filename.

If you want to display the only filename, run the grep command with -l option:

grep -rl ubuntu /mnt/grub.d/

You should see only filenames that match with search string:

You can also run the following command to display only filenames:

grep -H -R ubuntu /mnt/grub.d/ | cut -d: -f1

You should see the following output:

/mnt/grub.d/10_linux
/mnt/grub.d/10_linux
/mnt/grub.d/10_linux
/mnt/grub.d/10_linux
/mnt/grub.d/05_debian_theme
/mnt/grub.d/05_debian_theme

If you want to display only search string without filenames, run the grep command as shown below:

grep -rh ubuntu /mnt/grub.d/

You should see the following output:

ubuntu_recovery=»1″
Ubuntu|Kubuntu)
if [ «$ubuntu_recovery» = 1 ]; then
if ([ «$ubuntu_recovery» = 0 ] || [ x$type != xrecovery ]) && \
Tanglu|Ubuntu|Kubuntu)
Ubuntu|Kubuntu)

To ignore case when searching for a string, use grep command with -i option as shown below:

grep -ir ubuntu /mnt/grub.d/

You should see the following output:

/mnt/grub.d/10_linux:ubuntu_recovery=»1″
/mnt/grub.d/10_linux: Ubuntu|Kubuntu)
/mnt/grub.d/10_linux:if [ «$ubuntu_recovery» = 1 ]; then
/mnt/grub.d/10_linux: if ([ «$ubuntu_recovery» = 0 ] || [ x$type != xrecovery ]) && \
/mnt/grub.d/05_debian_theme: Tanglu|Ubuntu|Kubuntu)
/mnt/grub.d/05_debian_theme: # Set a monochromatic theme for Tanglu/Ubuntu.
/mnt/grub.d/05_debian_theme: Ubuntu|Kubuntu)

To Find Whole Words Only

To find all the lines that matches only whole words using the following syntax:

grep -wr «word» «/path-of-the-directory»

For example, find all the lines that matches for word “Ubuntu” in /mnt/grub.d directory.

grep -wr Ubuntu /mnt/grub.d/

You should see the following output:

/mnt/grub.d/10_linux: Ubuntu|Kubuntu)
/mnt/grub.d/05_debian_theme: Tanglu|Ubuntu|Kubuntu)
/mnt/grub.d/05_debian_theme: # Set a monochromatic theme for Tanglu/Ubuntu.
/mnt/grub.d/05_debian_theme: Ubuntu|Kubuntu)

If you want to search for two words “Ubuntu” and “Linux” in /mnt/grub.d directory, run the following command:

egrep -wr ‘Ubuntu|Linux’ /mnt/grub.d/

You should see the following output:

/mnt/grub.d/20_linux_xen: OS=GNU/Linux
/mnt/grub.d/20_linux_xen: OS=»$ GNU/Linux»
/mnt/grub.d/20_linux_xen:# the initrds that Linux uses don’t like that.
/mnt/grub.d/20_linux_xen: title=»$(gettext_printf «%s, with Xen %s and Linux %s (%s)» «$» «$» «$» «$(gettext «$«)»)»
/mnt/grub.d/20_linux_xen: title=»$(gettext_printf «%s, with Xen %s and Linux %s» «$» «$» «$«)»
/mnt/grub.d/20_linux_xen: lmessage=»$(gettext_printf «Loading Linux %s . » $
/mnt/grub.d/10_linux: OS=GNU/Linux
/mnt/grub.d/10_linux: Ubuntu|Kubuntu)
/mnt/grub.d/10_linux: OS=»$ GNU/Linux»
/mnt/grub.d/10_linux:# the initrds that Linux uses don’t like that.
/mnt/grub.d/10_linux: title=»$(gettext_printf «%s, with Linux %s (%s)» «$» «$» «$(gettext «$«)»)» ;;
/mnt/grub.d/10_linux: title=»$(gettext_printf «%s, with Linux %s» «$» «$«)» ;;
/mnt/grub.d/10_linux: if [ x»$title» = x»$GRUB_ACTUAL_DEFAULT» ] || [ x»Previous Linux versions>$title» = x»$GRUB_ACTUAL_DEFAULT» ]; then
/mnt/grub.d/10_linux: message=»$(gettext_printf «Loading Linux %s . » $
/mnt/grub.d/30_os-prober: if [ x»$title» = x»$GRUB_ACTUAL_DEFAULT» ] || [ x»Previous Linux versions>$title» = x»$GRUB_ACTUAL_DEFAULT» ]; then
/mnt/grub.d/05_debian_theme: Tanglu|Ubuntu|Kubuntu)
/mnt/grub.d/05_debian_theme: # Set a monochromatic theme for Tanglu/Ubuntu.
/mnt/grub.d/05_debian_theme: Ubuntu|Kubuntu)

Читайте также:  Видеокарта не совместима с windows 10 что делать

To display line numbers with matching words “Ubuntu”, use the grep command with -n option as shown below:

grep -wrn Ubuntu /mnt/grub.d/

You should see the following output:

/mnt/grub.d/10_linux:40: Ubuntu|Kubuntu)
/mnt/grub.d/05_debian_theme:32: Tanglu|Ubuntu|Kubuntu)
/mnt/grub.d/05_debian_theme:33: # Set a monochromatic theme for Tanglu/Ubuntu.
/mnt/grub.d/05_debian_theme:177: Ubuntu|Kubuntu)

Find all Lines that Starting with Lowercase or Uppercase Letter

To search for lines that start with an uppercase letter, use the following syntax:

grep «^[A-Z]» -rns «/path-of-the-directory»

To search for lines that start with a lowercase letter, use the following syntax:

grep «^[a-z]» -rns «/path-of-the-directory»

To search for lines that start with lowercase and uppercase letter, use the following syntax:

grep «^[a-zA-Z]» -rns «/path-of-the-directory»

Conclusion

Thats it for now. We hope you have now enough knowledge on how to use grep command to find a file containing a specific text. Feel free to ask any questions if you have any below in the comments.

Источник

Поиск текста в файлах 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 введите следующую команду:

Читайте также:  Как не создавать windows old

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 «7» /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. При правильном применении эта утилита станет мощным инструментом в ваших руках. Если у вас остались вопросы, пишите в комментариях!

Источник

Оцените статью