Find word in file linux

grep (GNU or BSD)

You can use grep tool to search recursively the current folder, like:

grep -r "class foo" .

Note: -r — Recursively search subdirectories.

You can also use globbing syntax to search within specific files such as:

grep "class foo" **/*.c

Note: By using globbing option (**), it scans all the files recursively with specific extension or pattern. To enable this syntax, run: shopt -s globstar. You may also use **/*.* for all files (excluding hidden and without extension) or any other pattern.

If you’ve the error that your argument is too long, consider narrowing down your search, or use find syntax instead such as:

find . -name "*.php" -execdir grep -nH --color=auto foo {} ';'

Alternatively, use ripgrep.

ripgrep

If you’re working on larger projects or big files, you should use ripgrep instead, like:

rg "class foo" .

Checkout the docs, installation steps or source code on the GitHub project page.

It’s much quicker than any other tool like GNU/BSD grep, ucg, ag, sift, ack, pt or similar, since it is built on top of Rust’s regex engine which uses finite automata, SIMD and aggressive literal optimizations to make searching very fast.

It supports ignore patterns specified in .gitignore files, so a single file path can be matched against multiple glob patterns simultaneously.


You can use common parameters such as:

  • -i — Insensitive searching.
  • -I — Ignore the binary files.
  • -w — Search for the whole words (in the opposite of partial word matching).
  • -n — Show the line of your match.
  • -C/--context (e.g. -C5) — Increases context, so you see the surrounding code.
  • --color=auto — Mark up the matching text.
  • -H — Displays filename where the text is found.
  • -c — Displays count of matching lines. Can be combined with -H.

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.

Read Also: 11 Advanced Linux ‘Grep’ Commands on Character Classes and Bracket Expressions

The command below will list all files containing a line with the text “check_root”, by recursively and aggressively searching the ~/bin directory.

$ grep -Rw ~/bin/ -e 'check_root'

Find a Word in Directory

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).

 
$ sudo grep -Rw / -e 'check_root'	

To ignore case distinctions employ the -i option as shown:

$ grep -Riw ~/bin/ -e 'check_root'

If you want to know the exact line where the string of text exist, include the -n option.

$ grep -Rinw ~/bin/ -e 'check_root'

Find String with Line Number

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.

$ grep -Rnw --include=*.sh ~/bin/ -e 'check_root'

In addition, it is possible to search for more than one pattern, using the following command.

$ grep -Rinw ~/bin/ -e 'check_root' -e 'netstat'

Find Multiple Words in Files

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.

Support Us

We are thankful for your never ending support.

By default, most search tools look at file names, not file contents. However, the most famous GNU search program, grep, will look inside files with the correct flags. Here we show you how you can find specific word(s) in a file on Linux.

Content

  • Using grep to Find a Specific Word in a File
  • Using find to Find a Specific Word in a File
  • Using ack to Find a Specific Word in a File
  • Want a GUI? Use Catfish
  • Frequently Asked Questions

By default, grep searches through the contents of files as well as their file names. It’s included on the majority of Linux systems and is generally identical across distros. Programmers looking through the file contents of their projects might prefer to run a different command, like ack.

Grep Recursivesearch

Depending on how the file is encoded, grep may not always be able to look inside. But for most text-based formats, grep can scan the text of the file for the specified pattern.

grep -rw '/path/to/search/' -e 'pattern'
  • The -r flag sets grep to recursive mode, navigating through all the directories contained within the specified directory.
  • The -w flag searches for whole word matches. This means that “red” will match only the actual word “red” rather than any string of letters containing it, like “redundant” or “tired.” It does this by looking only for “red” surrounded by what is known as non-word constituent characters (i.e., anything that isn’t a letter, number or underscore).
  • The -e flag prefaces the pattern to search for. It supports regular expressions by default.

To speed up grep, you can use the --exclude and --include flags to limit the search to certain types of files. For example, --exclude='*.csv' will not search within any files with the .csv extension. --include='*.txt', on the other hand, will only search within files with the .txt extension. The flag can be added immediately after the grep command as shown below:

grep --exclude='*.csv' -Rw '/path/to/search' -e 'pattern'

You can also exclude specified directories by following the format below:

grep --exclude-dir='{dir1,dir2,*_old}' -Rw '/path/to/search' -e 'pattern'

This command will not search in any directories in the present working directory named dir1, dir2, or matching the pattern *_old, eliminating them from the search process. It will execute the specified recursive, full-word match search on all other files in the present working directory.

Interesting Flags You Can Use With grep

Now that you have been properly acquainted with grep and how it works, here are some useful flags you can attach to your command:

  • -i – Makes grep do a non-case-sensitive search. For example, searching for “Kraken” will return a result when grep finds matches for “kraken” or “kRaken”.
  • -n – Show line numbers next to matches. This is especially useful for programmers or people looking through large config files.
  • -R – As with -r, grep will do a recursive search through all subfolders, but this specific flag will follow symbolic links (shortcuts).
  • -s – Suppresses error messages. If you’re getting many distracting errors about files that don’t exist, can’t be read, or have inappropriate permissions, pass this so that grep can stick to showing you matches it finds.

Using find to Find a Specific Word in a File

While the find command’s syntax is more complicated than grep, some prefer it.

find . -name "*.php" -exec grep "pattern" {} ;

This command will use find’s -exec flag to pass the found files to grep for searching. With a clever arrangement of syntax, you can use find‘s faster file-system search to locate the specific file types you want to search within, then pipe them to grep to search inside the files.

Grep Findcommand

Note that find only looks at filenames, not contents. That’s why grep is required to search file text and contents. The normal grep flags should be fully operational from within the -exec flag.

Using ack to Find a Specific Word in a File

The ack command is likely the fastest searching tool, but it’s not as popular as grep. The command below will search within the current directory.

If you want to search within a specific file or directory, you can append that file or fully-qualified pathname to your search.

ack 'pattern' /path/to/file.txt

Want a GUI? Use Catfish

If you’re allergic to terminals, all the popular Linux distros offer Catfish, a versatile GUI application that allows you to search files and their contents for a specific string. It isn’t as advanced as the commands discussed here, but it provides a valuable service to people who would prefer a graphical interface.

Grep Catfishgui

To search file contents for a specific word, click the menu on the top-right corner of Catfish and click on “Search file contents.”

Grep Catfishcontents

After you’ve set it up, type what you want to search for in the top bar and press Enter. That’s it!

Frequently Asked Questions

How do I stop a grep search before it’s done?

To stop any ongoing process in your terminal, simply press Ctrl + C on your keyboard. This sends a signal to terminate the running process. It’s also why you can’t use normal copy/paste shortcuts from within a terminal emulator.

Are there any file managers that search file contents?

If you use the KDE Plasma desktop environment, its default file manager (Dolphin) already has this capability. When you click the search button to look for files, there’s an option to choose between file names and file content underneath the search bar.

Just click on “Content” if you want to search for words within files. It won’t be as advanced as using grep, but it does the job.

Are there other uses for grep?

Grep isn’t just for searching your file system! Interestingly enough, you can pipe it through almost any command to search through its output instead of having to manually find something yourself.

Grep can be used to filter command output to show you things that are more relevant to you. Experiment enough with it and you’ll eventually master the art of diagnosing and getting to know your computer!

All screenshots by Miguel Leiva-Gomez.

Miguel Leiva-Gomez

Miguel Leiva-Gomez

Miguel has been a business growth and technology expert for more than a decade and has written software for even longer. From his little castle in Romania, he presents cold and analytical perspectives to things that affect the tech world.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

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

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

Что такое grep?

Название команды grep расшифровывается как «search globally for lines matching the regular expression, and print them». Это одна из самых востребованных команд в терминале Linux, которая входит в состав проекта GNU. До того как появился проект GNU, существовала утилита предшественник grep, тем же названием, которая была разработана в 1973 году Кеном Томпсоном для поиска файлов по содержимому в Unix. А потом уже была разработана свободная утилита с той же функциональностью в рамках GNU.

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

Синтаксис grep

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

$ grep [опции] шаблон [/путь/к/файлу/или/папке…]

Или:

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

Здесь:

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

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

Опции

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

  • -E, —extended-regexp — включить расширенный режим регулярных выражений (ERE);
  • -F, —fixed-strings — рассматривать шаблон поиска как обычную строку, а не регулярное выражение;
  • -G, —basic-regexp — интерпретировать шаблон поиска как базовое регулярное выражение (BRE);
  • -P, —perl-regexp — рассматривать шаблон поиска как регулярное выражение Perl;
  • -e, —regexp — альтернативный способ указать шаблон поиска, опцию можно использовать несколько раз, что позволяет указать несколько шаблонов для поиска файлов, содержащих один из них;
  • -f, —file — читать шаблон поиска из файла;
  • -i, —ignore-case — не учитывать регистр символов;
  • -v, —invert-match — вывести только те строки, в которых шаблон поиска не найден;
  • -w, —word-regexp — искать шаблон как слово, отделенное пробелами или другими знаками препинания;
  • -x, —line-regexp — искать шаблон как целую строку, от начала и до символа перевода строки;
  • -c — вывести количество найденных строк;
  • —color — включить цветной режим, доступные значения: never, always и auto;
  • -L, —files-without-match — выводить только имена файлов, будут выведены все файлы в которых выполняется поиск;
  • -l, —files-with-match — аналогично предыдущему, но будут выведены только файлы, в которых есть хотя бы одно вхождение;
  • -m, —max-count — остановить поиск после того как будет найдено указанное количество строк;
  • -o, —only-matching — отображать только совпавшую часть, вместо отображения всей строки;
  • -h, —no-filename — не выводить имя файла;
  • -q, —quiet — не выводить ничего;
  • -s, —no-messages — не выводить ошибки чтения файлов;
  • -A, —after-content — показать вхождение и n строк после него;
  • -B, —before-content — показать вхождение и n строк после него;
  • -C — показать n строк до и после вхождения;
  • -a, —text — обрабатывать двоичные файлы как текст;
  • —exclude — пропустить файлы имена которых соответствуют регулярному выражению;
  • —exclude-dir — пропустить все файлы в указанной директории;
  • -I — пропускать двоичные файлы;
  • —include — искать только в файлах, имена которых соответствуют регулярному выражению;
  • -r — рекурсивный поиск по всем подпапкам;
  • -R — рекурсивный поиск включая ссылки;

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

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

Давайте перейдём к практике. Сначала рассмотрим несколько основных примеров поиска внутри файлов Linux с помощью grep.

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

В первом примере мы будем искать информацию о пользователе root в файле со списком пользователей Linux /etc/passwd. Для этого выполните следующую команду:

grep root /etc/passwd

В результате вы получите что-то вроде этого:

С помощью опции -i можно указать, что регистр символов учитывать не нужно. Например, давайте найдём все строки содержащие вхождение слова time в том же файле:

grep -i "time" /etc/passwd

В этом случае Time, time, TIME и другие вариации слова будут считаться эквивалентными. Ещё, вы можете указать несколько условий для поиска, используя опцию -e. Например:

grep -e "root" -e "daemon" /etc/passwd

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

grep -n 'root' /etc/passwd

Это всё хорошо работает пока ваш поисковый запрос не содержит специальных символов. Например, если вы попытаетесь найти все строки, которые содержат символ «[» в файле /etc/grub/00_header, то получите ошибку, что это регулярное выражение не верно. Для того чтобы этого избежать, нужно явно указать, что вы хотите искать строку с помощью опции -F:

grep -F "[" /etc/grub.d/00_header

Теперь вы знаете как выполняется поиск текста файлах grep.

2. Фильтрация вывода команды

Для того чтобы отфильтровать вывод другой команды с помощью grep достаточно перенаправить его используя оператор |. А файл для самого grep указывать не надо. Например, для того чтобы найти все процессы gnome можно использовать такую команду:

ps aux | grep "gnome"

В остальном всё работает аналогично.

3. Базовые регулярные выражения

Утилита grep поддерживает несколько видов регулярных выражений. Это базовые регулярные выражения (BRE), которые используются по умолчанию и расширенные (ERE). Базовые регулярные выражение поддерживает набор символов, позволяющих описать каждый определённый символ в строке. Это: ., *, [], [^], ^ и $. Например, вы можете найти строки, которые начитаются на букву r:

grep "^r" /etc/passwd

Или же строки, которые содержат большие буквы:

grep "[A-Z]" /etc/passwd

А так можно найти все строки, которые заканчиваются на ready в файле /var/log/dmesg:

grep "ready$" /var/log/dmesg

Но используя базовый синтаксис вы не можете указать точное количество этих символов.

4. Расширенные регулярные выражения

В дополнение ко всем символам из базового синтаксиса, в расширенном синтаксисе поддерживаются также такие символы:

  • + — одно или больше повторений предыдущего символа;
  • ? — ноль или одно повторение предыдущего символа;
  • {n,m} — повторение предыдущего символа от n до m раз;
  • | — позволяет объединять несколько паттернов.

Для активации расширенного синтаксиса нужно использовать опцию -E. Например, вместо использования опции -e, можно объединить несколько слов для поиска вот так:

grep -E "root|daemon" /etc/passwd

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

5. Вывод контекста

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

grep -A4 "Error" /var/log/dmesg

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

grep -B4 "Error" /var/log/dmesg

Эта команда выведет строку со вхождением и 4 строчки до неё. А следующая выведет по две строки с верху и снизу от вхождения.

grep -C2 "Error" /var/log/dmesg

6. Рекурсивный поиск в grep

До этого мы рассматривали поиск в определённом файле или выводе команд. Но grep также может выполнить поиск текста в нескольких файлах, размещённых в одном каталоге или подкаталогах. Для этого нужно использовать опцию -r. Например, давайте найдём все файлы, которые содержат строку Kernel в папке /var/log:

grep -r "Kernel" /var/log

Папка с вашими файлами может содержать двоичные файлы, в которых поиск выполнять обычно не надо. Для того чтобы их пропускать используйте опцию -I:

grep -rI "Kernel" /var/log

Некоторые файлы доступны только суперпользователю и для того чтобы выполнять по ним поиск вам нужно запускать grep с помощью sudo. Или же вы можете просто скрыть сообщения об ошибках чтения и пропускать такие файлы с помощью опции -s:

grep -rIs "Kernel" /var/log

7. Выбор файлов для поиска

С помощью опций —include и —exclude вы можете фильтровать файлы, которые будут принимать участие в поиске. Например, для того чтобы выполнить поиск только по файлам с расширением .log в папке /var/log используйте такую команду:

grep -r --include="*.log" "Kernel" /var/log

А для того чтобы исключить все файлы с расширением .journal надо использовать опцию —exclude:

grep -r --exclude="*.journal" "Kernel" /var/log

8. Поиск слов в grep

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

grep -w "root" /etc/passwd

9. Количество строк

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

grep -c 'Kernel' /var/log/dmesg

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

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

grep -v nologin /etc/passwd

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

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

grep -lr 'Kernel' /var/log/

12. Цветной вывод

По умолчанию grep не будет подсвечивать совпадения цветом. Но в большинстве дистрибутивов прописан алиас для grep, который это включает. Однако, когда вы используйте команду c sudo это работать не будет. Для включения подсветки вручную используйте опцию —color со значением always:

sudo grep --color=always root /etc/passwd

Получится:

Выводы

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

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .


Posted:
September 23, 2022

Searching for patterns of text in files or text streams is one of the most common tasks you’ll perform in your sysadmin career. This is a valuable skill that allows you to check a variety of system configurations, analyze data, troubleshoot logs, and perform many other activities.

The most common way to find text in a Linux system is using the command-line utility grep. This utility was originally developed for the Unix operating system in the early 1970s. Grep evolved over the years, and the most common version available today for Linux, GNU grep, has additional features such as colored output. However, its main functionality is still the same.

Using grep, you can quickly find text matching a regular expression in a single file, a group of files, or text coming from stdin using the shell pipe operator.

This article covers how to use the grep command to find text.

Find text in a file

The most basic way to use grep is searching for text in a single file. To do this, type grep followed by the text pattern to search for and the file name to search in. For example, to find which port the Secure Shell (SSH) daemon uses, search for Port in file /etc/ssh/sshd_config:

$ grep Port /etc/ssh/sshd_config
Port 22
#GatewayPorts no

Notice that grep finds all lines that match the text pattern regardless of where the pattern is located.

[ Download the Linux grep command cheat sheet. ]

Extend grep with regular expressions

In the previous example, when you searched for Port in the SSH configuration file, grep returned two lines. The line you were looking for, Port 22, and an additional line containing the search pattern. In some cases, that’s exactly what you want. In other cases, grep could find too many entries that you’re not interested in, requiring you to sort through them to find the desired information.

To avoid that, you can use regular expressions to be more specific about what you’re looking for. For example, to find only lines that start with the word Port, you can use the regular expression operator ^, like this:

$ grep ^Port /etc/ssh/sshd_config
Port 22

This time grep returned only the line that started with Port since, in the second line, the expression Port is in the middle.

You can also use extended regular expressions with the command-line parameter -E. For example, to search for a pattern that contains the word Port followed by numbers, use this regular expression:

$ grep -E "Port [1-9]+" /etc/ssh/sshd_config
Port 22

You can also look for lines that end with a text pattern by using the $ operator. For example, to find all lines that end with none in sshd_config, use grep like this:

$ grep none$ /etc/ssh/sshd_config
#RekeyLimit default none
#AuthorizedPrincipalsFile none
#AuthorizedKeysCommand none
#ChrootDirectory none
#VersionAddendum none
#Banner none

Regular expressions are a big part of grep, making it powerful and flexible. However, regular expressions are a huge topic. For additional information, look at Regular expression on Wikipedia or Regular expressions 101.

Find text in multiple files and directories

Similar to finding text patterns in a single file, you can use grep to find text in multiple files or directories. To find text in multiple files simultaneously, specify which files to search from after the first file name, or use a shell wildcard such as * for all files. For example, to search for a configuration in two files:

$ grep Port /etc/ssh/sshd_config /etc/ssh/ssh_config
/etc/ssh/sshd_config:Port 22
/etc/ssh/sshd_config:#GatewayPorts no
/etc/ssh/ssh_config:#   Port 22

When you use multiple files, grep shows the name of the file where it found a match before showing the matched line.

[ Keep your most commonly used commands handy with the Linux commands cheat sheet. ]

To run the search recursively in multiple subdirectories, use the command line flag -R:

$ grep -R ^Port /etc
/etc/ssh/sshd_config:Port 22

The grep command is fast and returns results quickly, but it may take a long time if you specify too many files or subdirectories to search.

Find text in another command’s output

Similar to other Unix utilities, grep also acts on stdin when you pipe the output of another command into it. This is a fast and useful way to filter a command’s output to match the text pattern you’re looking for.

For example, if you want to check whether the package openssh is installed in your Fedora or Red Hat Enterprise Linux (RHEL) operating system, you can pipe the output of command rpm -qa, which lists all installed packages, into grep to search for the pattern:

$ rpm -qa | grep ssh
libssh-config-0.9.6-4.fc36.noarch
libssh-0.9.6-4.fc36.x86_64
openssh-8.8p1-1.fc36.1.x86_64

You can filter long command outputs with grep, making finding useful information easier.

[ Get the guide to installing applications on Linux. ]

Additional useful options

The grep command provides many options to change how it searches for patterns or displays results. So far in this article, you’ve seen some of them. While I can’t list all options, here are some other useful examples:

  • Use option -i for a case-insensitive search.

  • Use option -v to invert the search and display lines that do not match the pattern.
  • Use option -w to search for entire words only instead of patterns in the middle of other words.
  • Use option --color for colored output, making it easier to spot the matched pattern.

For a complete list of grep options, consult the man pages.

What’s next?

The GNU grep utility is flexible and useful, helping you accomplish many tasks in your daily sysadmin activities. The more you use grep, the more comfortable you will become, and soon you’ll notice you’re relying on it all the time.

For more information about grep, look at some of these links:

  • How to use grep
  • Linux grep command cheat sheet
  • Grep wiki
  • Grep manual at GNU

You can also find more information about grep in your Linux system by using man grep or quick, valuable examples with the tldr tool.

Here’s an overview of different methods that one can use for searching files for specific strings of text, with a few options added specifically to work only with text files, and ignore binary/application files.

One should note,however,that searching for word can get a little complex, because most line-matching tools will try to find a word anywhere on the line. If we’re talking about a word as string that could appear in the beginning or end of line, or alone on the line, or surrounded by spaces and/or punctuation — that’s when we’ll need regular expressions, and especially those that come from Perl. Here, for example, we can use -P in grep to make use of Perl regular expressions to surround it.

$ printf "A-well-a don't you know about the bird?nWell, everybody knows that the bird is a word" | grep -noP 'bbirdb'                                               
1:bird
2:bird

Simple grep

$ grep -rIH  'word'
  • -r for recursive search down from current directory
  • -I to ignore binary files
  • -H to output filename where match is found

Suitable for searching only.

find + grep

$ find -type f -exec grep -IH 'word' {} ;
  • find does the recursive search part
  • -I option is to ignore binary files
  • -H to output filename where line is found
  • good approach for combining with other commands within subshell, like:

    $ find -type f -exec sh -c 'grep -IHq "word" "$1" && echo "Found in $1"' sh {} ;
    

Perl

#!/usr/bin/env perl
use File::Find;
use strict;
use warnings;

sub find_word{
    return unless -f;
    if (open(my $fh, $File::Find::name)){
        while(my $line = <$fh>){
            if ($line =~ /bwordb/){
                printf "%sn", $File::Find::name;
                close($fh);
                return;
            }
        }
    }
}

# this assumes we're going down from current working directory
find({ wanted => &find_word, no_chdir => 1 },".")

poor-mans recursive grep in recursive bash script

This is the «bash way». Not ideal, probably no good reason to use this when you have grep or perl installed.

#!/usr/bin/env bash
shopt -s globstar
#set -x
grep_line(){
    # note that this is simple pattern matching 
    # If we wanted to search for whole words, we could use
    # word|word | word| word )
    # although when we consider punctuation characters as well - it gets more
    # complex
    case "$1" in
        *word*) printf "%sn" "$2";;
    esac
}
readlines(){
    #  line count variable can be used to output on which line match occured

    #line_count=1
    while IFS= read -r line;
    do
        grep_line "$line" "$filename"
        #line_count=$(($line_count+1))
    done < "$1"
}

is_text_file(){
    # alternatively, mimetype command could be used
    # with * text/* as pattern in case statement
    case "$(file -b --mime-type "$1")" in
        text/*) return 0;;
        *) return 1;;
    esac
}

main(){
    for filename in ./**/*
    do
        if [ -f "$filename" ] && is_text_file "$filename"
        then
            readlines "$filename"
        fi
    done
}
main "$@"

Понравилась статья? Поделить с друзьями:
  • Find word in array c
  • Find word from string java
  • Find word from picture
  • Find word from other words
  • Find word from letters program