How to Find a Specific String or Word in Files and Directories in Linux

LinuxOperating SystemFile System

Many times we need to search for a particular string which may be present in multiple files. In this article we'll see which commands to use to find all the files that contains a particular string or Word.

Using grep

It is a powerful regular expression search tool. At a basic level , it will match an input string with the list of files that contain that string.Below is the syntax and the example.

Example

grep ‘string’ directory-path/*.*
$ grep '<config' hadoop-2.6.5/etc/hadoop/*.*

Output

Running the above code gives us the following result −

Using grep -r

In this case we mention the r switch, which allows for a recursive search along all the subdirectories of the path given.

Example

grep -r ‘string’ directory-path/
$ grep -r 'done' hadoop-2.6.5/

Output

Running the above code gives us the following result −

Using egrep –r ‘word1|word2’

We can also search for multiple words by using the egrep command with | character. In the below example we are searching for files containing either the word config or the word comma.

Example

egrep -r ‘word1|word2’ directory-path/

Output

Running the above code gives us the following result −

raja
Published on 14-Feb-2020 10:42:14
Advertisements