Grep this word or that word

Question: Can you explain how to use OR, AND and NOT operators in Unix grep command with some examples?

Answer: In grep, we have options equivalent to OR and NOT operators. There is no grep AND opearator. But, you can simulate AND using patterns. The examples mentioned below will help you to understand how to use OR, AND and NOT in Linux grep command.

The following employee.txt file is used in the following examples.

$ cat employee.txt
100  Thomas  Manager    Sales       $5,000
200  Jason   Developer  Technology  $5,500
300  Raj     Sysadmin   Technology  $7,000
400  Nisha   Manager    Marketing   $9,500
500  Randy   Manager    Sales       $6,000

You already knew that grep is extremely powerful based on these grep command examples.

Grep OR Operator

Use any one of the following 4 methods for grep OR. I prefer method number 3 mentioned below for grep OR operator.

1. Grep OR Using |

If you use the grep command without any option, you need to use | to separate multiple patterns for the or condition.

grep 'pattern1|pattern2' filename

For example, grep either Tech or Sales from the employee.txt file. Without the back slash in front of the pipe, the following will not work.

$ grep 'Tech|Sales' employee.txt
100  Thomas  Manager    Sales       $5,000
200  Jason   Developer  Technology  $5,500
300  Raj     Sysadmin   Technology  $7,000
500  Randy   Manager    Sales       $6,000

2. Grep OR Using -E

grep -E option is for extended regexp. If you use the grep command with -E option, you just need to use | to separate multiple patterns for the or condition.

grep -E 'pattern1|pattern2' filename

For example, grep either Tech or Sales from the employee.txt file. Just use the | to separate multiple OR patterns.

$ grep -E 'Tech|Sales' employee.txt
100  Thomas  Manager    Sales       $5,000
200  Jason   Developer  Technology  $5,500
300  Raj     Sysadmin   Technology  $7,000
500  Randy   Manager    Sales       $6,000

3. Grep OR Using egrep

egrep is exactly same as ‘grep -E’. So, use egrep (without any option) and separate multiple patterns for the or condition.

egrep 'pattern1|pattern2' filename

For example, grep either Tech or Sales from the employee.txt file. Just use the | to separate multiple OR patterns.

$ egrep 'Tech|Sales' employee.txt
100  Thomas  Manager    Sales       $5,000
200  Jason   Developer  Technology  $5,500
300  Raj     Sysadmin   Technology  $7,000
500  Randy   Manager    Sales       $6,000

4. Grep OR Using grep -e

Using grep -e option you can pass only one parameter. Use multiple -e option in a single command to use multiple patterns for the or condition.

grep -e pattern1 -e pattern2 filename

For example, grep either Tech or Sales from the employee.txt file. Use multiple -e option with grep for the multiple OR patterns.

$ grep -e Tech -e Sales employee.txt
100  Thomas  Manager    Sales       $5,000
200  Jason   Developer  Technology  $5,500
300  Raj     Sysadmin   Technology  $7,000
500  Randy   Manager    Sales       $6,000

Grep AND

5. Grep AND using -E ‘pattern1.*pattern2’

There is no AND operator in grep. But, you can simulate AND using grep -E option.

grep -E 'pattern1.*pattern2' filename
grep -E 'pattern1.*pattern2|pattern2.*pattern1' filename

The following example will grep all the lines that contain both “Dev” and “Tech” in it (in the same order).

$ grep -E 'Dev.*Tech' employee.txt
200  Jason   Developer  Technology  $5,500

The following example will grep all the lines that contain both “Manager” and “Sales” in it (in any order).

$ grep -E 'Manager.*Sales|Sales.*Manager' employee.txt

Note: Using regular expressions in grep is very powerful if you know how to use it effectively.

6. Grep AND using Multiple grep command

You can also use multiple grep command separated by pipe to simulate AND scenario.

grep -E 'pattern1' filename | grep -E 'pattern2'

The following example will grep all the lines that contain both “Manager” and “Sales” in the same line.

$ grep Manager employee.txt | grep Sales
100  Thomas  Manager    Sales       $5,000
500  Randy   Manager    Sales       $6,000

Grep NOT

7. Grep NOT using grep -v

Using grep -v you can simulate the NOT conditions. -v option is for invert match. i.e It matches all the lines except the given pattern.

grep -v 'pattern1' filename

For example, display all the lines except those that contains the keyword “Sales”.

$ grep -v Sales employee.txt
200  Jason   Developer  Technology  $5,500
300  Raj     Sysadmin   Technology  $7,000
400  Nisha   Manager    Marketing   $9,500

You can also combine NOT with other operator to get some powerful combinations.

For example, the following will display either Manager or Developer (bot ignore Sales).

$ egrep 'Manager|Developer' employee.txt | grep -v Sales
200  Jason   Developer  Technology  $5,500
400  Nisha   Manager    Marketing   $9,500

Bash’s elegant simplicity seems to get lost in it’s huge man page.

In addition to the excellent solutions above, I thought I’d try to give you a cheat sheet on how bash parses and interprets statements. Then using this roadmap I’ll parse the examples presented by the questioner to help you better understand why they don’t work as intended.


Note: Shell script lines are used directly. Typed input-lines are first history-expanded.

Each bash line is first tokenized, or in other words chopped into what are called tokens. (Tokenizing occurs before all other expansions, including brace, tilde, parameter, command, arithmetic, process, word splitting, & filename expansion.)

A token here means a portion of the input line separated (delimited) by one of these special meta-characters:

space,  - White space...
tab, 
newline,

‘<’,    - Redirection & piping...
‘|’, 
‘>’
‘&’,    - And/Both < | > | >>  .or.  &<file descriptor>

‘;’,    - Command termination

‘(’,    - Subshell, closed by -     ‘)’

Bash uses many other special characters but only these 10 produce the initial tokens.

However because these meta-characters also sometimes must be used within a token, there needs to be a way to take away their special meaning. This is called escaping. Escaping is done either by quoting a string of one or more characters, (i.e. 'xx..', "xx.."), or by prefixing an individual character with a back-slash, (i.e. x). (It’s a little more complicate than this because the quotes also need to be quoted, and because double quotes don’t quote everything, but this simplification will do for now.)

Don’t confuse bash quoting with the idea of quoting a string of text, like in other languages. What is in between quotes in bash are not strings, but rather sections of the input line that have meta-characters escaped so they don’t delimit tokens.

Note, there is an important difference between ', and ", but that’s for another day.

The remaining unescaped meta-characters then become token separators.

For example,

$ echo "x"'y'g
xyg

$ echo "<"'|'>
<|>

$ echo x; echo y
x; echo y

In the first example there are two tokens produced by a space delimiter: echo and xyz.

Likewise in the 2nd example.

In the third example the semicolon is escaped, so there are 4 tokens produced by a space delimiter, echo, x;, echo, and y. The first token is then run as the command, and takes the next three tokens as input. Note the 2nd echo is not executed.


The important thing to remember is that bash first looks for escaping characters (', ", and ), and then looks for unescaped meta-character delimiters, in that order.

If not escaped then these 10 special characters serve as token delimiters. Some of them also have additional meaning, but first and foremost, they are token delimiters.


What grep expects

In the example above grep needs these tokens, grep, string, filename.

The question’s first try was:

$ grep (then|there) x.x

In this case (, ) and | are unescaped meta characters and so serve to split the input into these tokens: grep, (, then, |, there, ), and x.x. grep wants to see grep, then|there, and x.x.

The question’s second try was:

grep «(then|there)» x.x

This tokenizes into grep, (then|there), x.x. You can see this if you swap out grep for echo:

echo «(then|there)» x.x
(then|there) x.x

INTRODUCTION

Among the many useful Kali-Linux tools to know how to use, grep is important for searching for certain text or files. In many instances, grep is a basic command to know for getting the most use out of a Linux or Unix system, but its applications to ethical hacking are limitless. To begin, we will officially define what the grep tool is:

WHAT IS GREP & WHAT ARE ITS APPLICATIONS?

Grep is a command line Linux tool that is used to search for text or files based on matching patterns. By searching for a specific pattern with grep, this will cause any matching pattern to be printed as an output to the command line. Grep stands for “global regular expression print” and was created in 1974 as an original tool for Unix OS by computer scientist, Ken Thompson. Besides searching for text or files for the sake of searching, grep can be used to perform important tasks for ethical hacking. For example: In many Capture The Flag (CTF) competitions, it is usually a challenge to have to search for a “flag” or string of hidden text within a large text file. The grep command can be used to solve this challenge. On another occasion, grep can also be a method for hackers to analyze a target’s contents, such as searching for specific keywords to lead to further private information.

GREP COMMANDS

In this tutorial, we will be demonstrating a few essential grep commands that can be performed on any Linux or Unix system. Let’s begin!

GREP MANUAL

As usual, when first getting acquainted with using a tool on Kali-Linux, it is always a good idea to consult the manual for that command to learn a little more about it. The “man” command in Linux allows a user to view all instructions and applications for a specific command. Within this tutorial, we include several teachings of the Kali-Linux manual for the grep command.

man grep

SEARCH FOR TEXT IN A TEXT FILE

The most basic grep command to know is how to search for text in a text file. The simple command to perform this action is:

grep times tale2cities.txt

This command searches for the text pattern “times” within a text file named “tale2cities.txt” and returns the matched pattern highlighted in red.

SEARCH FOR WORD

The “-w” argument selects only those lines that match the word inputted, and is useful to search for words separated by spaces. The command is represented by the following:

grep -w despair tale2cities.txt

This returns an output of all instances of the word “despair” within the file tale2cities.txt. 

EXTENDED REGULAR EXPRESSION: ERE (EGREP/ GREP -E)

egrep or grep -E is a type of regular grep expression that matches the pattern specified in the input to the pattern within a file or text. The grep command has three possible versions of regular expressions: Basic (BRE), extended (ERE), and Perl (PRCE). In this tutorial, we will currently be focusing on the applications of egrep (ERE):

SEARCH FOR LINE BEGINNING WITH CERTAIN TEXT

Using the egrep command, a user can search for a line of text beginning with a certain letter, word, or string. To perform this action, type the following command:

grep -E ‘bI’ tale2cities.txt 

The output results in searching for all lines of text that start with the uppercase letter “I”:

GREP OPERATORS

In computer programming, it is common to learn about the standard AND, OR, XOR, NAND, NOR boolean operators for writing code. The principle is the same when writing commands with grep, but instead of using the habitual signage belonging to these operators, grep commands must use a vertical line called a “pipe”:   |  . The most common operators that we will be covering with grep are the AND and OR operators, as well as the NOT grep operator represented by the argument “-v”.

AND OPERATOR

The AND operator conjoins two arguments with a pipe symbol, telling the grep command to search for the text “times” in the file “tale2cities.txt” as well as the word “was” within the same file.

egrep “times|was” tale2cities.txt

OR OPERATOR

The OR operator tells the grep command to search for one of two operators using the dash and pipe symbols. Here in this example, grep is told to search for either “times” or the word “was” in the file “tale2cities.txt”. 

grep -e times -e was tale2cities.txt

The output produced displays both words “times” and “was” because both are included within the file’s contents. However, when we search for the words “times” and “blue”, only the word “times” is displayed with the OR operator because “blue” does not exist within the file.

grep -e times -e blue tale2cities.txt

EXCLUSIVE SEARCH (GREP “NOT” OPERATOR)

Using the “-v” argument with grep excludes certain words from a search, outputting all other content besides the inputted word. The “-v” command represents selecting the non-matching lines of text in a text file. For example:

grep -v Nmap output.txt

This command excludes the word “Nmap” from a routine Nmap report scan. As you can see, there is no existence of the word “Nmap” in the output. 

SEARCH RECURSIVELY

A recursive search in Linux or Unix searches the contents of all directories, subdirectories, and files of the system to find the matching pattern input. Even if there are hundreds or even thousands of files within a system, a recursive search will go through all hierarchies to return the desired content. The recursive search is represented with the argument “-r”. It is shown on the command line by typing:

grep -r times 

Since no starting directory is given, the command will search through all directories recursively, following path lines to retrieve files or content that include the word “times”. 

LIST ALL SPECIFIC FILE NAMES 

To search for all file names that include specific text or strings, we use the “-l” argument, shown below:

grep -r ‘times’ -l

As we discussed previously, the “-r” argument is the “recursive search” command that tells grep to do a system wide search while narrowing down its output to only specific files that contain the word ‘times’.

LIST ALL FILES WITHOUT MATCH

The “-L” argument does the opposite of the “-l” argument in a grep search by listing all the file names that do not match the input. For example, the below command returns all file names that do not include ‘times’ in their contents:

grep -r ‘times’ -L

The file list is thus noticeably much longer when not including certain file names:

COLORIZE GREP SEARCH

Since grep is such a useful tool for analyzing information, the “colorize grep” command further improves this task by highlighting multiple keywords. Like annotating a physical book, the “–color” argument makes it easier to view certain information. In the below command, all the letters of “a” are highlighted:

grep –color a tale2cities.txt

COUNT NUMBER OF STRINGS

Imagine that you had to search for a certain string and report the exact number of times that it had occurred within a file. To perform this action, the “-c” argument is used, which stands for “count”. This command prints the exact number of lines matching the input. We see that after typing the following command, the string “open” occurs 3 times, and when we cat into the output.txt file, we can verify this count:

grep -c open output.txt

REVERSE COUNT NUMBER OF STRINGS

As demonstrated before, entering the “-v” argument along with a grep command does a reverse search of the matching input. By adding “-v” with a count argument, we are able to return the number of strings that do not match a specific input:

grep -c -v open ouput.txt

Demonstrated in the output, the number of strings that do not match “open” equals 20.

SEARCH FOR CASE-INSENSITIVE STRINGS

The grep command searches for words case sensitively by default, so if you wanted to search for a certain word in which it does not matter whether it is uppercase or lowercase, you would use the “-i” argument:

grep -i Nmap output.txt

The “-i” argument ignores case distinctions with the grep command. The previous command thus tells grep to search for all existences of “Nmap” regardless of the word starting with an upper or lowercase letter.

CONCLUSION

Hopefully, you have enjoyed this tutorial of basic grep commands. When used appropriately, grep can be a highly powerful tool that is able to fetch important information. You can practice using the grep command with any Linux or Unix system, and can always consult the grep manual for more information. Have fun searching!

SOURCES

  • poftut.com. “Introduction to Linux Grep Commands With Examples”. By Ismail Baydan.
  • cyberciti.biz. nixcraft. “Search Multiple Words / String Pattern Using grep Command on Bash Shell”. By Vivek Gite.
  • thegeekstuff.com. “7 Linux Grep OR, Grep AND, Grep NOT Operator Examples”. By Ramesh Natarajan.

Introduction

The grep command, which stands for «global regular expression print,» is one of Linux’s most powerful and widely used commands.

grep looks for lines that match a pattern in one or more input files and outputs each matching line to standard output. grep reads from the standard input, which is usually the output of another command, if no files are specified.

In this tutorial, you will use grep command that looks for lines that match a pattern in one or more input files and outputs.

grep Command Syntax

The grep command has the following syntax:

grep [OPTIONS] PATTERN [FILE...]

Optional items are those in square brackets.

  • File — Names of one or more input files.
  • PATTERN — Look for a pattern.
  • OPTIONS — A set of zero or more choices. grep has a lot of settings that govern how it behaves.

    The user performing the command must have read access to the file in order to search it.

In Files, Look for a String

The grep command’s most basic use is to look for a string (text) in a file.

For example, to see all the entries in the /etc/passwd file that contains the string bash, use the following command:

grep bash /etc/passwd

This is what the output should look like:

root:x:0:0:root:/root:/bin/bash
vega:x:1000:1000:vega:/home/vega:/bin/bash

If the string contains spaces, use single or double quotation marks to surround it:

grep "Gnome Display Manager" /etc/passwd

Invert Match (Exclude)

Use the -v (or --invert-match) option to display lines that do not match a pattern.

To print the lines that do not contain the string nologin, for example, type:

grep -v nologin /etc/passwd
Output

root:x:0:0:root:/root:/bin/bash
colord:x:124:124::/var/lib/colord:/bin/false
git:x:994:994:git daemon user:/:/usr/bin/git-shell
vega:x:1000:1000:vega:/home/vega:/bin/bash

Use Grep to Filter the Output of a Command

The output of a command can be filtered using grep and pipe, with just the lines matching a specific pattern being printed on the terminal.

You can use the ps command to see which processes are running on your system as user www-data, for example:

ps -ef | grep www-data
Output

www-data 18247 12675  4 16:00 ?        00:00:00 php-fpm: pool www
root     18272 17714  0 16:00 pts/0    00:00:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn www-data
www-data 31147 12770  0 Oct22 ?        00:05:51 nginx: worker process
www-data 31148 12770  0 Oct22 ?        00:00:00 nginx: cache manager process

You can also use a single command to bring in several pipes. There is also a line in the output above that contains the grep process, as you can see. Pass the output to another grep instance as described below if you don’t want that line to be displayed.

ps -ef | grep www-data | grep -v grep
Output

www-data 18247 12675  4 16:00 ?        00:00:00 php-fpm: pool www
www-data 31147 12770  0 Oct22 ?        00:05:51 nginx: worker process
www-data 31148 12770  0 Oct22 ?        00:00:00 nginx: cache manager process

Recursive Search

Invoke grep with the -r option to recursively search for a pattern (or --recursive). When this option is supplied, grep will scan all files in the specified directory, skipping any recursively encountered symlinks.

Instead of -r, use the -R option to follow all symbolic links (or --dereference-recursive).

Here’s an example of how to search all files in the /etc directory for the string vegastack.com:

grep -r vegastack.com /etc

You will get an output like below:

Output

/etc/hosts:127.0.0.1 node2.vegastack.com
/etc/nginx/sites-available/vegastack.com:    server_name vegastack.com   www.vegastack.com;

grep will follow all symbolic links if you use the -R option:

grep -R vegastack.com /etc

Take note of the output’s last line. Because files in Nginx’s sites-enabled directory are symlinks to configuration files in the sites-available directory, that line is not shown when grep is run with -r.

Output

/etc/hosts:127.0.0.1 node2.vegastack.com
/etc/nginx/sites-available/vegastack.com:    server_name vegastack.com   www.vegastack.com;
/etc/nginx/sites-enabled/vegastack.com:    server_name vegastack.com   www.vegastack.com;

Show Only the Filename

Use the -l (or --files-with-matches) option to suppress the default grep output and only print the names of files containing the matched pattern.

The command below searches the current working directory for all files ending in .conf and prints just the names of the files that contain the string vegastack.com:

grep -l vegastack.com *.conf

You will get an output like below:

tmux.conf
haproxy.conf

Usually, the -l option is combined with the recursive option -R:

grep -Rl vegastack.com /tmp

Case Insensitive Search

grep is case-sensitive by default. The uppercase and lowercase characters are treated separately in this scenario.

When using grep, use the -i option to ignore case when searching (or --ignore-case).

When searching for Zebra without any options, for example, the following command will not return any results, despite the fact that there are matching lines:

grep Zebra /usr/share/words

However, if you use the -i option to perform a case-insensitive search, it will match both upper and lower case letters:

grep -i Zebra /usr/share/words

«Zebra» will match «zebra», «ZEbrA», or any other upper and lower case letter combination for that string.

zebra
zebra's
zebras

Search for Full Words

grep will display all lines where the string is embedded in larger strings while searching for a string.

If you search for «gnu,» for example, you’ll find all lines where «gnu» is embedded in larger terms like «cygnus» or «magnum»:

grep gnu /usr/share/words
Output

cygnus
gnu
interregnum
lgnu9d
lignum
magnum
magnuson
sphagnum
wingnut

Use the -w (or --word-regexp) option to return only lines where the provided string is a whole word (contained by non-word characters).

🤔

Alphanumeric characters (a-z, A-Z, and 0-9) and underscores (_) make up word characters. Non-word characters are all the rest of the characters.

If you execute the same program with the -w option, the grep command will only return lines that contain the word gnu as a distinct word.

grep -w gnu /usr/share/words
Output

gnu

Show Line Numbers

The -n (or --line-number) option instructs grep to display the line number of lines containing a pattern-matching string. grep prints the matches to standard output, prefixed with the line number, when this option is used.

You may use the following command to display the lines from the /etc/services file containing the string bash prefixed with the corresponding line number:

grep -n 10000 /etc/services

The matches are found on lines 10123 and 10124, as seen in the output below.

Output

10123:ndmp            10000/tcp
10124:ndmp            10000/udp

Count Matches

Use the -c (or --count) option to print a count of matching lines to standard output.

We’re measuring the number of accounts that use /usr/bin/zsh as a shell in the example below.

regular expression
grep -c '/usr/bin/zsh' /etc/passwd
Output

4

Quiet Mode

The -q (or --quiet) option instructs grep to execute in silent mode, with no output to the standard output. The command leaves with status 0 if a match is found. This is handy when using grep in shell scripts to check if a file contains a string and then conduct a specific action based on the result.

Here’s an example of using grep as a test command in an if statement in quiet mode:

if grep -q PATTERN filename
then
    echo pattern found
else
    echo pattern not found
fi

Basic Regular Expression

Basic, Extended, and Perl-compatible regular expression feature sets are available in GNU Grep.

grep interprets the pattern as a basic regular expression by default, with all characters except the meta-characters being regular expressions that match each other.

The following is a list of the most prevalent meta-characters:

  • To match a phrase at the beginning of a line, use the ^ (caret) symbol. The string kangaroo will only match in the following example if it appears at the very beginning of a line.
grep "^kangaroo" file.txt
  • To match an expression at the end of a line, use the $ (dollar) sign. In the example below, the string kangaroo will only match if it appears at the end of a line.
grep "kangaroo$" file.txt
  • To match a single character, use the . (period) sign. For example, you could use the following pattern to match anything that starts with kan, then has two characters, and ends with the string roo:
grep "kan..roo" file.txt
  • To match any single character wrapped in brackets, use [] (brackets). To discover the lines that contain the words «accept» or «accent,» apply the following pattern:
grep "acce[np]t" file.txt
  • To match any single character that isn’t enclosed in brackets, use []. The following pattern will match any combination of strings containing co(any letter except l) a, such as coca, cobalt, and so on, but not cola.
grep "co[^l]a" file.txt

Use the (backslash) symbol to get around the next character’s specific meaning.

Extended Regular Expressions

Use the -E (or --extended-regexp) option to interpret the pattern as an extended regular expression. To generate more complicated and powerful search patterns, extended regular expressions include all of the fundamental meta-characters as well as additional meta-characters. Here are a few examples:

  • All email addresses in a given file are matched and extracted:
grep -E -o "b[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+.[A-Za-z]{2,6}b" file.txt
  • From a given file, find and extract all valid IP addresses:
grep -E -o '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' file.txt

Only the matching string is printed using the -o option.

Search for Multiple Strings (Patterns)

The OR operator | can be used to connect two or more search patterns.

grep reads the pattern as a normal regular expression by default, which means that meta-characters like | lose their special significance and should be replaced with their backslashed variants.

We’re looking for all occurrences of the words fatal, error, and critical in the Nginx log error file in the example below:

grep 'fatal|error|critical' /var/log/nginx/error.log

The operator | should not be escaped if you use the extended regular expression option -E, as demonstrated below:

grep -E 'fatal|error|critical' /var/log/nginx/error.log

Print Lines Before a Match

Use the -B (or --before-context) option to print a certain number of lines before matching lines.

For example, you could use the following command to display five lines of leading context before matching lines:

grep -B 5 root /etc/passwd

Print Lines After a Match

Use the -A (or --after-context) option to output a certain number of lines following matching lines.

For example, you could use the following command to display five lines of trailing context after matching lines:

grep -A 5 root /etc/passwd

Conclusion

You can use the grep command to look for a pattern within files. If grep finds a match, it outputs the lines that contain the provided pattern.

The Grep User’s Manual page has a lot more information on grep.

If you have any queries, please leave a comment below and we’ll be happy to respond to them.

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.

Понравилась статья? Поделить с друзьями:
  • Grep file for word
  • Greeting word new year
  • Greeting word in english
  • Greeting word for email
  • Greeting word for christmas card