Linux search all files for word

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.

Contents

1. Search text files with the grep tool
2. SearchMonkey
3. Recoll
4. DocFetcher
5. Regexxer

For Linux users, the need to search for words in one or multiple files arises quite often.

There are many different applications that can do a good job for you. Which application will be most suitable for you depends on your needs and preferences. The applications are mainly distinguished by the following characteristics:

  • Command line tools vs. tools with a graphical interface.
  • Whether they are able to search only in text files, or in all commonly used document types.
  • Whether they use indexing or not.

In this article we will introduce you to different types of search applications, so that you can choose the most suitable one for you.

Note: If you are a Mac user, you can take a look at our article How to Search Text in Your Documents on Mac.

1. Search text files with the grep tool

About the grep tool

The most popular command-line tool for searching text in Linux is grep. It was created more than 45 years ago! Its developer is the American computer scientist Ken Thompson.

Grep can search in all kinds of text files (.txt, .html, .xml, etc.), but cannot search in other types of documents such as OpenOffice files, PDF files and others.

In fact, the grep command is in the top 15 of the most used commands in Linux, according to Hostinger.

The utility is supported by the UNIX, Linux, and Mac operating systems.

There is also a Windows alternative to grep called findstr, which you can read more about in our article How to Search Files in Windows 10.

How to use the grep tool

The grep tool is built into the operating system, so you don’t need to install it.

The simplest syntax to find a string in a single file using the grep command is:
grep ‘searched-word’ filename

By default, the search with grep is case sensitive.

Let’s gradually add the most useful options to our search.

 
1. Make the search case-insensitive with the «-i» option:
grep -i ‘searched-word’ filename

 
2. Search recursively in all files in a given directory with the «-r» option:
grep -ir ‘searched-word’ ‘/directory’

 
3. Search whole words only with the «-w» option:
grep -irw ‘searched-word’ ‘/directory’

 
4. Print the line numbers in which the searched word was found with the «-n» option:
grep -irwn ‘searched-word’ ‘/directory’

 
5. Search for multiple words syntax:
grep -ir ‘word1|word2|word3’ ‘/directory’

Many other useful grep options can be found in the official Grep Manual.

Advantages and disadvantages of the grep tool

 
Like any software tool, along with the convenience it gives to you, grep has some drawbacks. Let’s summarize its pros and cons.
 

Pros:

  • Great flexibility through a wide range of options.
  • Works effectively with regular expressions.
  • It is built into the operating system.

Cons:

  • Cannot search in any other types of documents except text files.
  • Doesn’t have a graphical interface.
  • Difficult reading of long lines of text in the results.
  • Not so powerful for searching in source code, compared to ack.

2. SearchMonkey

SearchMonkey is a free and open source GUI application for Linux OS, which uses the capabilities of the grep tool. SearchMonkey is also available for Windows and Mac users.

In addition to searching in text files, SearchMonkey supports:

  • OpenOffice and LibreOffice files (.odt).
  • Microsoft Office files (.docx).
  • PDF files (.pdf).

The tool can search a directory recursively and returns the file names and the highlighted content that you search.

Go through the following steps to install and use the tool:

 
1. Install the application with the following command in the Terminal:
sudo apt install searchmonkey

 
2. Launch the application.

 
3. Choose the folder to be searched.

 

 
4. Check the «Containing» checkbox, enter your search words and press «Enter.»

 

 
5. Click on a file from the list on the left pane to see the fragments of text found.

 

If you want to search a specific directory, click on the “Advanced” tab and choose the desired folder.

In the «Advanced» pane, you can use additional criteria to filter the results such as by the file size, date of last modification, and others.

With SearchMonkey, you can also use regular expressions in the same way as in the grep tool.
 

Pros:

  • Completely free and open source.
  • Lightweight and easy to use.
  • Doesn’t use indexing.
  • Many options for refinement of the search.
  • Works with regular expressions.

Cons:

  • Slow performance, not suitable for big directories.
  • Does not support RTF, Excel (.xlsx, .xls), PowerPoint (.pptx, .ppt), old Word (.doc) and other popular document types.
  • Cannot search for a combination of words that occur in one sentence.
  • Doesn’t show all lines from the results in one place, you have to check each file one by one.

3. Recoll

Recoll is a desktop search tool, available for Linux, Windows, and MacOS. The Linux version is free. It can search not only in text files, but also in most common document formats including:

  • OpenOffice and LibreOffice files (.odt).
  • Microsoft Office files (.docx, .xlsx, .xls, .ppt).
  • PDF files (.pdf).
  • AbiWord files (.abw).

By default, Recoll indexes the files on your «home» directory, which can take some time.

Here are the steps to install and use the program:

 
1. Install Recoll with the command:
sudo apt-get install recoll

 
2. Launch the application.

 
3. On the «First indexing setup» window click on «Start indexing now.»

 

 
4. On the «Missing helper programs» message click «OK.»

 

 
5. Type your search terms and press «Enter.»

6. From the results list, click on «snippets» to see all text fragments containing the searched words.

 

7. On the «Snippets» window, you see the pages and the lines in which your searched words are found.

 

If you need to search in a folder outside your «home» directory, go to «File» -> «Special indexing» and click on the «Browse» button to select the desired directory.

Pros

  • Free for Linux users.
  • Supports most common document types.
  • Easy-to-use graphical interface.
  • Supports advanced search options.
  • Allows document preview without opening the file.

Cons

  • Although the application uses indexing, the searches are relatively slow.
  • Does not support the Word 97-2003 «.doc» format or the PowerPoint «.pptx» file format.
  • Cannot search for a combination of words.
  • You have to click on each result’s «snippets» to see the fragments found.

4. DocFetcher

DocFetcher is a free and open source desktop search tool, available for Linux, Windows, and MacOS. In addition to text file formats, it supports almost all of the document formats which you may use:

  • Microsoft Office 97-2003 files (.doc, .xls, .ppt).
  • Microsoft Office 2007-365 files (.docx, .xlsx, .pptx, .docm, .xlsm, .pptm).
  • Microsoft Outlook email files (.pst).
  • OpenOffice files (.odt, .ods, .odg, .odp, .ott, .ots, .otg, .otp).
  • PDF files (.pdf).
  • Rich Text Format (.rtf).
  • AbiWord files (.abw, .zabw).
  • And others.

Here are brief instructions for using DocFetcher:

 
1. Install DocFetcher with the command:
sudo snap install docfetcher

2. Launch DocFetcher
 

3. Right-click on the «Search Scope» pane at the bottom left and choose «Create index from»->»Folder.»

 

4. Choose a folder, give a name to the index and click the «Run» button.

 

5. Wait until the index is created. When it is ready, you will see a check mark in the «Search Scope» pane on the left.

 

 
6. Type your search words and press «Enter.»

 
7. Click on a file name to see the fragments of the text containing your searched words. You can navigate in the results with the «up» and «down» arrows.

 

Pros

  • Free and open source application.
  • It has a portable version.
  • It can search in archive formats (.zip, .7z, .rar, .tar).
  • Offers additional search options – wildcards, similar words, proximity search and others.

Cons

  • Creating an index can take a long time for large folders.
  • Cannot perform case-insensitive search.
  • The navigation in the text results is not user-friendly.
  • Cannot search for a combination of words in a sentence.

5. Regexxer

The regexxer application provides rich possibilities for using perl-style regular expressions. It is a free and open source application with a user-friendly graphical interface, created in 2002.

Regexxer is available only for Linux, and you can most easily install it in Debian and Ubuntu.

Here’s how you can use Regexxer:
 

1. Install the application with the command:
sudo apt-get install regexxer

 
2. Launch the application, select a search folder and make sure the «recursive» checkbox is selected.

3. Click the «Find files» button.

 

4. Type your search terms in the «Search» box and click the «Find» button.

 

 
5. Use the arrows at the bottom to navigate in the results.

 

 
6. In the left pane you can see the number of results found in the corresponding files, and in the right pane, the text containing the searched words.

Pros:

  • Completely free and open source.
  • Easy to install and use.
  • Simple and intuitive graphical interface.
  • Supports all types of perl-style regular expressions.
  • Highlights the searched words in the results.
  • Doesn’t use indexing.

Cons:

  • Regexxer is slower than other similar applications.
  • Sometimes becomes unresponsive or closes unexpectedly.
  • Cannot search in any other types of documents except text files.
  • Cannot search for a combination of words that occur in one sentence.

Conclusion

I hope you enjoyed this guide to finding text files in Linux.

I am fully aware that many more things can be added for the presented applications, and also that there are many other useful tools in this niche.

Now I would like to hear from you: which of the presented applications is most useful for you? Do you have any problems using these tools? Do you want to add anything else that is important on this topic?

Let me know your thoughts by posting a comment in the comments section below.

About the author

Dimitar is a software developer and entrepreneur with over 20 years of experience in software development and online marketing.

Содержание

  1. How to Find Text in Files in Linux
  2. Finding text in files
  3. Find text in files using grep
  4. Basic search
  5. Regular expression
  6. Extended regular expression
  7. Finding text in files
  8. Grep GUI
  9. Find text in files using nano
  10. Find text in files using Vim
  11. Find text in files using GNOME Text Editor
  12. Find text in files using VS Code
  13. Final thoughts
  14. About the author
  15. Sidratul Muntaha
  16. Find Files Containing Specific Text in Linux
  17. Find files containing specific text with mc
  18. Author: Sergey Tkachenko
  19. 6 thoughts on “Find Files Containing Specific Text in Linux”
  20. Поиск текста в файлах Linux
  21. Что такое grep?
  22. Синтаксис grep
  23. Опции
  24. Примеры использования
  25. Поиск текста в файлах
  26. Вывести несколько строк
  27. Регулярные выражения в grep
  28. Рекурсивное использование grep
  29. Поиск слов в grep
  30. Поиск двух слов
  31. Количество вхождений строки
  32. Инвертированный поиск в grep
  33. Вывод имени файла
  34. Цветной вывод в grep
  35. Выводы
  36. Linux / UNIX Recursively Search All Files For A String
  37. How to use grep command to recursively search All files for a String
  38. Following symtlinks
  39. Case sensitive recursive search
  40. Displaying files name when searching for a string/word
  41. Using find command to search recursively
  42. Finding all files containing specific text on Linux
  43. How to search only files that have specific extensions
  44. Understanding grep command options that used for searching text files
  45. Summing up
  46. Common Linux Text Search
  47. 1. Overview
  48. 2. The grep Command
  49. 3. Common Usage of grep
  50. 3.1. Basic String Search
  51. 3.2. Case-Insensitive Search
  52. 3.3. Whole-Word Search
  53. 4. Advanced grep Usage
  54. 4.1. Regular Expressions
  55. 4.2. Fixed String Search
  56. 4.3. Inverting the Search
  57. 4.4. Print Only the Matched Parts
  58. 5. Other grep Tricks
  59. 5.1. Print Additional Context Lines Before or After Match
  60. 5.2. Count the Matching Lines
  61. 5.3. Recursively Search a Directory
  62. 6. Conclusion

How to Find Text in Files in Linux

For a system administrator, working with text files is a common phenomenon. Maybe need to find a specific section from piles of log files for troubleshooting something? Or, need to find the document that contains essential information quickly?

In the case of Linux, there are numerous methods to find texts in files. It’s possible using both built-in tools and 3rd-party apps. Check out how to find texts in files in Linux.

Finding text in files

Depending on the number of files you have to perform a search on, there are two ways to perform the text search: automated or manual. If you have to work with a couple of text files, the manual search is more suitable. However, if there are hundreds of text files, then the automated search is the most efficient.

For automated search, we’ll be using grep. Grep comes pre-installed on any Linux distro. As for manual search, any modern text editor will do the job.

Find text in files using grep

In Linux, grep is the default tool for searching texts. Its name is derived from the ed command g/re/p that stands for “globally search for a regular expression and print matching lines.” It’s available on any modern Linux distro.

Grep is a command-line tool. Its command structure is as follows.

As the name of grep suggests, the pattern to search for is described using a regular expression. The regular expression is a special type of string that describes a pattern to match, locate, and manage. To learn more about grep and regular expression, check out using grep and egrep with regular expression.

For demonstration purposes, grab a sample text file. In this example, download the GNU General Public License v3.0 text file.

Basic search

The fundamental way of using grep is to search for a basic string.

Take a look at the following grep command. It’ll search for the word “GNU” in the text file.

image1 24

To show the line number, use the “-n” flag.

image3 22

To perform a case-insensitive search using grep, use the “-i” flag.

image2 27

You may not want to see the search matches but only the file name where the match happened in some situations. To print only the filename, use the “-l” flag. Here, the asterisk denotes to use all the text files in the current directory.

image5 19

We can also pipe the output of other commands to grep.

image4 23

Regular expression

Regex offers a smart way of fine-tuning the search. It has its own rules. However, different applications and programming languages implement regular expression differently. Here are a couple of examples that you can use with grep.

To define that the string is to be found at starting a line, use the caret (^) symbol.

image7 14

To define that the string is to be found at the end of a line, use the dollar sign ($).

image6 16

To describe that there can be any character at a certain location of the pattern, use the period character (.). For example, the expression “G.U” is valid if there’s any character between “G” and “U”.

image9 10

To describe that there can be a subset of characters at a particular location of the pattern, use the brackets ([]). For example, the expression “t[wo]o” tells that the match is valid for “two” and “too” only.

image8 11

Extended regular expression

As the name suggests, an extended regular expression can do more complex things than basic regular expressions. To use extended regular expression with grep, you have to use the “-E” flag.

To search for two different strings, use the OR operators (|).

image12 7

Finding text in files

Now comes the main part. Instead of manually telling grep the file to perform the search on, grep can do it automatically. In the following command, grep will use all the available text files in the current directory for searching the pattern.

If you want to grep to perform the search on a different directory, then you have to specify the location.

image10 10

If there are folders, grep doesn’t explore them by default. To tell grep to search recursively, use the “-R” flag.

image11 10

Grep GUI

If you prefer to work with GUI but still want to enjoy grep’s features, then check out searchmonkey. It’s a front-end solution for grep. The package is available on almost all the major Linux distros.

image13 7

Find text in files using nano

GNU Nano is a simple and powerful text editor that comes with any Linux distro. It has built-in features to search for text in a text file.

Note that in this method, you have to open the text file, and search manually. It’s doable if there’s only a handful of text files to work with. If there’s more, then using grep is the most optimal choice.

Open the text file in nano.

image14 7

To search for a string match, press “Ctrl + W”. After typing the string to search for, press “Enter”.

image15 8

Find text in files using Vim

Vim is a well-known and reputed text editor. It’s the command-line equivalent of a modern text editor. Vim comes with numerous advanced features like plugins, macros, auto-completion, filters, etc.

Similar to nano, Vim works with a single file at a time. If you have multiple text files, then using grep is the most optimal way to go.

To search in a text file, first, open it in Vim.

image16 7

Enter the following Vim command and hit “Enter”.

image17 7

Find text in files using GNOME Text Editor

The GNOME Text Editor is the text editor that comes with the GNOME desktop. It’s a simplistic text editor with all the basic features you’d expect. It’s a nice alternative to the command-line text editors.

Similar to nano and vim, the same caution applies to this method. If the number of text files is large, then you better stick with grep.

Open the text file in Text Editor. Press “Ctrl + F” to bring up the search bar.

image18 5

Find text in files using VS Code

Visual Studio Code is a powerful text editor with tons of features. It’s optimized for programmers to be used as if it’s a full-fledged IDE. It’s available on almost all the major Linux distros.

Install the Visual Studio Code snap package.

image19 5

Open the text file in VS Code. Press “Ctrl + F” to start searching.

image20 5

Final thoughts

There are numerous ways to search text in files. It’s an easy task to master. It’s strongly recommended to master the grep command because it offers the most value in terms of efficiency and ease-of-use.

If you prefer GUI, then there are numerous text editors to choose from. Any modern text editor will provide the text search option.

profile photo 1

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.

Источник

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.

catfish

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.

grep search file contents

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

mc search file contents

Fill in the «Content:» section and press the Enter key. It will find all files with the required text.

mc search results

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.

mc search results panelize

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:

If you like this article, please share it using the buttons below. It won’t take a lot from you, but it will help us grow. Thanks for your support!

Author: 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. View all posts by Sergey Tkachenko

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.

Источник

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

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

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

Что такое grep?

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

Синтаксис grep

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

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

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

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

Опции

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

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

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

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

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

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

grep User /etc/passwd

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

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

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

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

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

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

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

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

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

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 «1» /var/log/Xorg.0.log

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

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

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

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

Поиск слов в grep

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

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

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

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

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

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

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

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

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

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

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

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

Snimok ekrana ot 2020 05 12 17 43 52

Выводы

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

Источник

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

How to use grep command to recursively search All files for a String

Following symtlinks

Case sensitive recursive search

Displaying files name when searching for a string/word

Using find command to search recursively

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

Sample outputs from the last command:

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

Finding all files containing specific text on Linux

How to search only files that have specific extensions

Understanding grep command options that used for searching text files

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

Источник

Common Linux Text Search

Last modified: November 8, 2020

1. Overview

Searching text is a very common operation in Linux. For example, we want to find the files that contain specific text, or we want to find the lines within a file that contains specific text.

In this tutorial, we’ll go through some examples together and learn how to perform some common text searching in Linux using the grep command-line utility.

2. The grep Command

The grep command searches one or more input files for lines containing a match to a specified pattern.

Its name comes from the ed command g/re/p (globally search a regular expression and print).

By default, grep outputs the matching lines. The grep command has different variants and is available on almost every distribution of the Unix-like system by default. In this tutorial, we’ll focus on the most widely used GNU grep.

3. Common Usage of grep

Now let’s see some practical examples of how grep helps us to do text searches. In this section, all examples are done with GNU grep version 3.3.

Let’s create a text file named input.txt to help us explore the grep command’s results:

3.1. Basic String Search

To see how simple it is to perform a basic text search using grep, let’s search our file for lines containing the string “linux“:

Quoting the search string is a good practice. Whether to use a single or double quote depends on if we want the shell to expand the expression before executing the grep process.

3.2. Case-Insensitive Search

The basic string search with grep is pretty simple. What if we want to search lines containing “linux” or “Linux” — that is, do a case-insensitive search? grep‘s -i option can help us with that:

We can see that all lines containing linux or Linux are listed.

3.3. Whole-Word Search

We can use the -w option to tell grep to treat the pattern as a whole word.

For example, let’s find lines in our input file that contain “is” as a whole word:

Note that the lines containing the word “this” – but not the word “is” – were not included in the result.

4. Advanced grep Usage

4.1. Regular Expressions

If we’ve understood the meaning of grep‘s name, it’s not hard to imagine that regular expressions (regex) and grep are good friends. GNU grep understands three different versions of regular expression syntax:

In GNU grep, there is no difference in functionality between the basic and extended syntaxes. However, PCRE gives additional functionality and is more powerful than both BRE and ERE.

By default, grep will use BRE. In BRE, the meta-characters ?, +, <, |, (, and ) lose their special meanings. We can use the backslash-escaped versions ?, +, <, |, (, and ) to make them have special meanings.

With the -E option, grep will work with ERE syntax. In ERE, the meta-characters we mentioned above have special meanings. If we backslash-escape them, they lose their special meanings.

Finally, the -P option will tell grep to do pattern matching with PCRE syntax.

4.2. Fixed String Search

We’ve learned that grep will do a BRE search by default. So the pattern “linux” or “is” that we gave in the previous examples are regex as well. They don’t have any characters with special meaning. Therefore, they match the literal text “linux” and “is“.

If the text we want to search contains any characters with special meaning in regex (for example, “.” or “*“), we have to either escape those characters or use the -F option, to tell grep to do a fixed-string search.

For example, we may want to search for lines containing “*/opt*“:

Let’s do the same without using the -F option:

4.3. Inverting the Search

We can use grep to search lines that don’t contain a certain pattern. Let’s see an example that finds all lines that don’t contain numbers:

8 in the above example is a regex that matches on a single numerical digit.

If we switch to PCRE with the -P option, we can use d to match a numerical digit and get the same result:

In the outputs of the above two commands, we see that empty lines are also matched because blank lines don’t have numerical digits either.

4.4. Print Only the Matched Parts

As we can see, grep prints each line that matches a pattern. However, sometimes only the matched parts are interesting for us. We can make use of the -o option to tell grep to print only matched parts of a matching line.

For example, we may want to find all strings that look like directories:

5. Other grep Tricks

5.1. Print Additional Context Lines Before or After Match

Sometimes we want to see lines before or after our matching lines in the result. grep has three options to handle additional context lines: -B (before a match), -A (after a match), and -C (before and after a match).

Now, let’s search for the text “report” and print the three lines after the matching line:

The context line control options can be handy when we want to check several continuous lines but only know one line among them matching some pattern.

For example, YAML is widely used in applications for configuration files. Instead of viewing the entire configuration file, we might only need to see part of it. For example, to see the datasource configuration in a YAML file, we can make use of grep‘s -A option:

5.2. Count the Matching Lines

The -c option in grep allows us to suppress the standard output, and instead print only the count of matching lines. For example, we want to know how many lines contain “*”:

grep is a line-based search utility. The -c option will output the count of matched lines instead of the count of pattern occurrences. That’s why the above command outputs three instead of six.

5.3. Recursively Search a Directory

In addition to files, grep accepts a directory as input as well. A common problem is to search in a directory recursively and find all files that contain some pattern.

Let’s search in the /var/log directory recursively to find all files that contain “boot”. Here, we’ll use the -l option to skip the matching information and let grep print only the file names of matched files:

6. Conclusion

In this article, we’ve learned how to use the grep command to do simple text searches and how to control the output.

Simply put, we’ve seen how grep finds text efficiently and quickly and is a great tool to have in our arsenal of Linux commands.

Источник

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 "$@"

Like this post? Please share to your friends:
  • Linux replace word file
  • Link excel with sql server
  • Linux open office word
  • Link excel with access
  • Linux find word in all files