Showing posts with label Grep Command. Show all posts
Showing posts with label Grep Command. Show all posts

Thursday, 22 October 2020

grep command in Unix/Linux

Grep Command, Unix Command, Linux Command, LPI Study Materials

The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for globally search for regular expression and print out).

Syntax:


grep [options] pattern [files]

Options Description

-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
 with each such part on a separate output line.

Sample Commands


Consider the below file as an input.

$cat > lpicentral.txt

unix is great os. unix is opensource. unix is free os.
learn operating system.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

1. Case insensitive search : The -i option enables to search for a string case insensitively in the give file. It matches the words like “UNIX”, “Unix”, “unix”.

$grep -i "UNix" lpicentral.txt

Output:

unix is great os. unix is opensource. unix is free os.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

2. Displaying the count of number of matches : We can find the number of lines that matches the given string/pattern

$grep -c "unix" lpicentral.txt

Output:

2

3. Display the file names that matches the pattern : We can just display the files that contains the given string/pattern.

$grep -l "unix" *

or

$grep -l "unix" f1.txt f2.txt f3.xt f4.txt

Output:

lpicentral.txt

4. Checking for the whole words in a file : By default, grep matches the given string/pattern even if it found as a substring in a file. The -w option to grep makes it match only the whole words.

$ grep -w "unix" lpicentral.txt

Output:

unix is great os. unix is opensource. unix is free os.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

5. Displaying only the matched pattern : By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option.

$ grep -o "unix" lpicentral.txt

Output:

unix
unix
unix
unix
unix
unix

6. Show line number while displaying the output using grep -n : To show the line number of file with the line matched.

$ grep -n "unix" lpicentral.txt

Output:

1:unix is great os. unix is opensource. unix is free os.
4:uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

7. Inverting the pattern match : You can display the lines that are not matched with the specified search sting pattern using the -v option.

$ grep -v "unix" lpicentral.txt

Output:

learn operating system.
Unix linux which one you choose.

8. Matching the lines that start with a string : The ^ regular expression pattern specifies the start of a line. This can be used in grep to match the lines which start with the given string or pattern.

$ grep "^unix" lpicentral.txt

Output:

unix is great os. unix is opensource. unix is free os.

9. Matching the lines that end with a string: The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern.

$ grep "os$" lpicentral.txt

10. Specifies expression with -e option. Can use multiple times :

$grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" lpicentral.txt

Grep Command, Unix Command, Linux Command, LPI Study Materials

11. -f file option Takes patterns from file, one per line.

$cat pattern.txt

Agarwal
Aggarwal
Agrawal

$grep –f pattern.txt  lpicentral.txt

Saturday, 22 August 2020

A BIG collection of Unix/Linux ‘grep’ command examples

Grep Command, LPI Tutorial and Materials, LPI Exam Prep, LPI Certification, LPI Learning

Linux grep FAQ: Can you share some Linux/Unix grep command examples?

Sure. The name grep means "general regular expression parser", but you can think of the grep command as a “search” command for Unix and Linux systems: It’s used to search for text strings and regular expressions within one or more files.

I think it’s easiest to learn how to use the grep command by showing examples, so let’s dive right in.

.

.

.

this space intentionally left blank because of the long Table of Contents over there (and my poor CSS skills) -->

.

.

.

.

Abridged grep command examples


First up, if you don’t like reading a bunch of text and just want to see a collection of grep commands, this section is for you.

(If the Table of Contents over there on the right side is still in the way, click or tap the ‘hide’ link in its title to hide it):

search for a string in one or more files
----------------------------------------
grep 'fred' /etc/passwd              # search for lines containing 'fred' in /etc/passwd
grep fred /etc/passwd                # quotes usually not when you don't use regex patterns
grep null *.scala                    # search multiple files


case-insensitive
----------------
grep -i joe users.txt                # find joe, Joe, JOe, JOE, etc.


regular expressions
-------------------
grep '^fred' /etc/passwd             # find 'fred', but only at the start of a line
grep '[FG]oo' *                      # find Foo or Goo in all files in the current dir
grep '[0-9][0-9][0-9]' *             # find all lines in all files in the current dir with three numbers in a row


display matching filenames, not lines
-------------------------------------
grep -l StartInterval *.plist        # show all filenames containing the string 'StartInterval'
grep -il StartInterval *.plist       # same thing, case-insensitive


show matching line numbers
--------------------------
grep -n we gettysburg-address.txt    # show line numbers as well as the matching lines


lines before and after grep match
---------------------------------
grep -B5 "the living" gettysburg-address.txt        # show all matches, and five lines before each match
grep -A10 "the living" gettysburg-address.txt       # show all matches, and ten lines after each match
grep -B5 -A5 "the living" gettysburg-address.txt    # five lines before and ten lines after


reverse the meaning
-------------------
grep -v fred /etc/passwd             # find any line *not* containing 'fred'
grep -vi fred /etc/passwd            # same thing, case-insensitive


grep in a pipeline
------------------
ps auxwww | grep httpd               # all processes containing 'httpd'
ps auxwww | grep -i java             # all processes containing 'java', ignoring case
ls -al | grep '^d'                   # list all dirs in the current dir


search for multiple patterns
----------------------------
egrep 'apple|banana|orange' *                                                         # search for multiple patterns, all files in current dir
egrep -i 'apple|banana|orange' *                                                      # same thing, case-insensitive
egrep 'score|nation|liberty|equal' gettysburg-address.txt                             # all lines matching multiple patterns
locate -i calendar | grep Users | egrep -vi 'twiki|gif|shtml|drupal-7|java|PNG'       # oh yeah

multiple search strings, multiple filename patterns
---------------------------------------------------
grep -li "jtable" $(find . -name "*.java,v" -exec grep -li "prevayl" {} \;)           # find all files named "*.java,v" containing both
                                                                                      # 'prevayl' and 'jtable'

grep + find
-----------
find . -type f -exec grep -il 'foo' {} \;     # print all filenames of files under current dir containing 'foo', case-insensitive


recursive grep search
---------------------
grep -rl 'null' .                             # similar to the previous find command; does a recursive search
grep -ril 'null' /home/al/sarah /var/www      # search multiple dirs
egrep -ril 'aja|lpicentral' .                      # multiple patterns, recursive


grep gzip files
---------------
zgrep foo myfile.gz                           # all lines containing the pattern 'foo'
zgrep 'GET /blog' access_log.gz               # all lines containing 'GET /blog'
zgrep 'GET /blog' access_log.gz | more        # same thing, case-insensitive

That's the short version of the grep examples. The rest of this document describes many of these examples.

Searching for a text string in one file


This first grep command example searches for all occurrences of the text string 'fred' within the /etc/passwd file. It will find and display all of the lines in this file that contain the text string fred, including lines that contain usernames like "fred", and also other strings like "alfred":

grep 'fred' /etc/passwd

In a simple example like this, the quotes around the string fred aren't necessary, but they are needed if you're searching for a string that contains spaces, and will also be needed when you get into using regular expressions (search patterns).

Searching for a string in multiple files


Grep Command, LPI Tutorial and Materials, LPI Exam Prep, LPI Certification, LPI Learning
Our next grep command example searches for all occurrences of the text string joe within all files of the current directory:

grep 'joe' *

The '*' wildcard matches all files in the current directory, and the grep output from this command will show both (a) the matching filename and (b) all lines in all files that contain the string 'joe'.

As a quick note, instead of searching all file with the "*" wildcard, you can also use grep to search all files in the current directory that end in the file extension .txt, like this:

grep 'joe' *.txt


Case-insensitive file searching with the Unix grep command


To perform a case-insensitive search with the grep command, just add the -i option, like this:

grep -i score gettysburg-address.txt

This grep search example matches the string "score", whether it is uppercase (SCORE), lowercase (score), or any mix of the two (Score, SCore, etc.).

Reversing the meaning of a grep search


You can reverse the meaning of a Linux grep search with the -v option. For instance, to show all the lines of my /etc/passwd file that don't contain the string fred, I'd issue this command:

grep -v fred /etc/passwd


Using grep in a Unix/Linux command pipeline


The grep command is often used in a Unix/Linux pipeline. For instance, to show all the Apache httpd processes running on my Linux system, I use the grep command in a pipeline with the ps command:

ps auxwww | grep httpd

This returns the following output:

root     17937  0.0  0.0  14760  6880 ?        Ss   Apr01   0:39 /usr/local/apache/bin/httpd -k start
nobody   21538  0.0  0.0  24372 17108 ?        S    Apr03   0:01 /usr/local/apache/bin/httpd -k start
nobody   24481  0.0  0.0  14760  6396 ?        S    Apr03   0:00 /usr/local/apache/bin/httpd -k start
nobody   26089  0.0  0.0  24144 16876 ?        S    Apr03   0:01 /usr/local/apache/bin/httpd -k start
nobody   27842  0.0  0.0  24896 17636 ?        S    Apr03   0:00 /usr/local/apache/bin/httpd -k start
nobody   27843  0.0  0.0  24192 16936 ?        S    Apr03   0:00 /usr/local/apache/bin/httpd -k start
nobody   27911  0.0  0.0  23888 16648 ?        S    Apr03   0:01 /usr/local/apache/bin/httpd -k start
nobody   28280  0.0  0.0  24664 17256 ?        S    Apr03   0:00 /usr/local/apache/bin/httpd -k start
nobody   30404  0.0  0.0  24360 17112 ?        S    Apr03   0:00 /usr/local/apache/bin/httpd -k start
nobody   31895  0.0  0.0  14760  6296 ?        S    Apr03   0:00 /usr/local/apache/bin/httpd -k start
root     31939  0.0  0.0   1848   548 pts/0    R+   Apr03   0:00 grep http

(I deleted about half of the "httpd -k start" lines from that output manually to save a little space.)

Similarly, here's how you can find all the Java processes running on your system using the ps and grep commands in a Unix pipeline:

ps auxwww | grep -i java

In this example I've piped the output of the ps auxwww command into my grep command. The grep command only prints the lines that have the string "java" in them; all other lines from the ps command are not printed.

One way to find all the sub-directories in the current directory is to mix the Linux ls and grep commands together in a pipe, like this:

ls -al | grep '^d'

Here I'm using grep to list only those lines where the first character in the line is the letter d.

Using the Linux grep command to search for multiple patterns at one time (egrep)


You can use a different version of the grep command to search for multiple patterns at one time. To do this, just use the egrep command instead of grep, like this:

egrep 'score|nation|liberty|equal' gettysburg-address.txt

This Unix egrep command searches the file named gettysburg-address.txt for the four strings shown (score, nation, liberty, and equal). It returns any lines from the file that contain any of those words.

I should also note that "egrep" stands for "extended grep", and as you can see, it lets you do things like searching for multiple patterns at one time.

Searching for regular expressions (regex patterns) with grep


Of course the Linux grep command is much more powerful than this, and can handle very powerful regular expressions (regex patterns). In a simple example, suppose you want to search for the strings "Foo" or "Goo" in all files in the current directory. That grep command would be:

grep '[FG]oo' *

If you want to search for a sequence of three integers with grep you might use a command like this:

grep '[0-9][0-9][0-9]' *

This next grep command searches for all occurrences of the text string fred within the /etc/passwd file, but also requires that the "f" in the name "fred" be in the first column of each record (that's what the caret character tells grep). Using this more-advanced search, a user named "alfred" would not be matched, because the letter "a" will be in the first column:

grep '^fred' /etc/passwd

Regular expressions can get much, much more complicated (and powerful) than this, so I'll just leave it here for now.

Display only filenames with a grep search


If you're looking through a lot of files for a pattern, and you just want to find the names of the files that contain your pattern (or "patterns", as shown with egrep) -- but don't want to see each individual grep pattern match -- just add the -l (lowercase letter L) to your grep command, like this:

grep -l StartInterval *.plist

This command doesn't show every line in every file that contains the string "StartInterval"; it just shows the names of all the files that contain this string, like this:

com.apple.atrun.plist
com.apple.backupd-auto.plist
com.apple.dashboard.advisory.fetch.plist
com.apple.locationd.plist
org.amavis.amavisd_cleanup.plist

Of course you can also combine grep command arguments, so if you didn't happen to know how to capitalize "StartInterval" in that previous example, you could just add the -i argument to ignore case, like this:

grep -il startinterval *.plist

and that would have worked just fine as well, returning the same results as the previous grep command example.

Showing matching line numbers with Linux grep


To show the line numbers of the files that match your grep command, just add the -n option, like this:

grep -n we gettysburg-address.txt

Searching my sample gettysburg-address.txt file, I get the following output from this command:

9:Now we are engaged in a great civil war,
22:that we should do this.
24:But in a larger sense we can not dedicate -
25:we can not consecrate -
26:we can not hallow this ground.
29:have consecrated it far above our poor power
33:what we say here,
43:we take increased devotion to that cause
46:that we here highly resolve that these dead

grep before/after - Showing lines before or after your grep pattern match


After a recent comment, I just learned that you can display lines before or after your grep pattern match, which is also very cool. To display five lines before the phrase "the living" in my sample document, use the -B argument, like this:

grep -B 5 "the living" gettysburg-address.txt

This grep command example returns this output:

The world will little note,
nor long remember,
what we say here,
but can never forget what they did here.

It is for us, the living,

Similarly, to show the five lines after that same search phrase, use the -A argument with your Unix grep command, like this:

grep -A 5 "the living" gettysburg-address.txt

This grep "after" command returns the following output:

It is for us, the living,
rather to be dedicated here
to the unfinished work which they have,
thus far, so nobly carried on.
It is rather for us to be here
dedicated to the great task remaining before us -

Of course you can use any number after the -A and -B options, I'm just using the number five here as an example.

Power file searching with find and grep


A lot of times I know that the string "foo" exists in a file somewhere in my directory tree, but I can't remember where. In those cases I roll out a power command, a Linux find command that uses grep to search what it finds:

find . -type f -exec grep -il 'foo' {} \;

This is a special way of mixing the Linux find and grep commands together to search every file in every subdirectory of my current location. It searches for the string "foo" in every file below the current directory, in a case-insensitive manner. This find/grep command can be broken down like this:

◉ "." means "look in the current directory"
◉ -type f means "look in files only"
◉ -exec grep -il foo means "search for the string 'foo' in a case-insensitive manner, and return the matching line and filename when a match is found
◉ {} \; is a little bizarre syntax that you need to add to the end of your find command whenever you add the -exec option. I try to think of it as a placeholder for the filenames the find command finds.

Note that on Mac OS X systems you may be able to use the mdfind command instead of this find/grep combination command. The mdfind command is a command-line equivalent of the Spotlight search functionality.

Tuesday, 21 April 2020

An `egrep` example with multiple regular expressions

Linux Tutorial and Material, Linux Guides, Linux Certifications, Linux egrep, LPI Exam Prep

Summary: How to use the Linux egrep command with multiple regular expressions (regex patterns).

As a quick note here today, I just used the Linux egrep command to perform a case-insensitive search on multiple regular expressions (regex patterns). Really, what I did was a little more complicated:

locate -i calendar | grep Users | egrep -vi 'twiki|gif|shtml|drupal-7|java|PNG'

As you can see from that command, I did this:

◉ Used to locate command with the case-insensitive option to find all files with the string "calendar" in them.

◉ Used the grep command so the output would only display files and directories with the string "Users" in them.

◉ Used the egrep command with multiple regex patterns to reduce the output much more. I used the -v argument to perform the "opposite" meaning of a normal egrep command, so strings with these patterns were not shown; and also used the -i argument to perform a case insensitive egrep search here.

While my original locate -i calendar command shows nearly 3,000 files, the locate command combined with grep and egrep in this manner shows only 15 files.

An easier egrep command


Before I go away, here's an easier egrep command to look at:

egrep 'apple|banana|orange' *

That egrep command searches for those three strings (regular expressions, really) in all files in the current directory. This next command does the same thing, but in a case-insensitive manner:

egrep -i 'apple|banana|orange' *

Thursday, 26 December 2019

Linux: Regular Expression in grep

grep Command, Linux Tutorial and Materials, Linux Certifications, Linux Online Exam, Linux Prep

Prerequisite: Grep

Basic Regular Expression


Regular Expression provides an ability to match a “string of text” in a very flexible and concise manner. A “string of text” can be further defined as a single character, word, sentence or particular pattern of characters.

Like the shell’s wild–cards which match similar filenames with a single expression, grep uses an expression of a different sort to match a group of similar patterns.

◉ [ ]: Matches any one of a set characters
◉ [ ] with hyphen: Matches any one of a range characters
◉ ^: The pattern following it must occur at the beginning of each line
◉ ^ with [ ] : The pattern must not contain any character in the set specified
◉ $: The pattern preceding it must occur at the end of each line
◉ . (dot): Matches any one character
◉ \ (backslash): Ignores the special meaning of the character following it
◉ *: zero or more occurrences of the previous character
◉ (dot).*: Nothing or any numbers of characters.

Examples


(a) [ ] : Matches any one of a set characters

1. $grep  “New[abc]”  filename

It specifies the search pattern as :

Newa , Newb or Newc

2. $grep  “[aA]g[ar][ar]wal”  filename

It specifies the search pattern as

Agarwal , Agaawal , Agrawal , Agrrwal

agarwal , agaawal , agrawal , agrrwal

(b) Use [ ] with hyphen: Matches any one of a range characters

1. $grep  “New[a-e]” filename

It specifies the search pattern as

Newa , Newb or Newc , Newd, Newe

2. $grep  “New[0-9][a-z]”  filename

It specifies the search pattern as: New followed by a number and then an alphabet.

New0d, New4f etc

(c ) Use ^: The pattern following it must occur at the beginning of each line

1. $grep  “^san”  filename

Search lines beginning with san. It specifies the search pattern as

sanjeev ,sanjay, sanrit , sanchit , sandeep etc.

2. $ls –l |grep  “^d”

Display list of directories only

3. $ls –l |grep  “^-”

Display list of regular files only

(d) Use ^ with [ ]: The pattern must not contain any character in the set specified

1. $grep  “New[^a-c]”  filename

It specifies the pattern containing the word “New” followed by any character other than an ‘a’,’b’, or ‘c’

2. $grep  “^[^a-z A-Z]”  filename

Search lines beginning with an non-alphabetic character

(e) Use $: The pattern preceding it must occur at the end of each line

$ grep "vedik$" file.txt

(f) Use . (dot): Matches any one character

$ grep "..vik" file.txt
$ grep "7..9$" file.txt

(g) Use \ (backslash): Ignores the special meaning of the character following it

1. $ grep "New\.\[abc\]" file.txt

It specifies the search pattern as New.[abc]

2. $ grep "S\.K\.Kumar" file.txt

It specifies the search pattern as

S.K.Kumar

(h) Use *: zero or more occurrences of the previous character

$ grep "[aA]gg*[ar][ar]wal" file.txt

(i) Use (dot).*: Nothing or any numbers of characters.

$ grep "S.*Kumar" file.txt

Thursday, 5 December 2019

Grep Command In Unix/Linux With Simple Examples

Grep Command, Linux Tutorial and Material, Linux Certification, LPI Online Exam

Grep command in Unix/Linux is the short form of ‘global search for the regular expression’.

The grep command is a filter that is used to search for lines matching a specified pattern and print the matching lines to standard output.

Grep Command in Unix with Examples


Syntax:

grep [options] [pattern] [file]

The pattern is specified as a regular expression. A regular expression is a string of characters that is used to specify a pattern matching rule. Special characters are used to define the matching rules and positions.

#1) Anchor Characters: ‘^’ and ‘$’ at the beginning and end of the pattern are used to anchor the pattern to the start of the line, and to the end of the line respectively.

Example: “^Name” matches all lines that start with the string “Name”. The strings “\<” and “\>” are used to anchor the pattern to the start and end of a word respectively.

#2) Wildcard Character: ‘.’ Is used to match any character.

Example:“^.$” will match all lines with any single character.

#3) Escaped Characters: Any of the special characters can be matched as a regular character by escaping them with a ‘\’.

Example: “\$\*” will match the lines that contain the string “$*”

#4) Character Range: A set of characters enclosed in a ‘[‘ and ‘]’ pair specify a range of characters to be matched.

Example: “[aeiou]” will match all lines that contain a vowel. A hyphen can be used while specifying a range to shorten a set of consecutive characters. E.g. “[0-9]” will match all lines that contain a digit. A carat can be used at the beginning of the range to specify a negative range. E.g. “[^xyz]” will match all lines that do not contain x, y or z.

#5) Repetition Modifier: A ‘*’ after a character or group of characters is used to allow matching zero or more instances of the preceding pattern.

The grep command supports a number of options for additional controls on the matching:

◉ -i: performs a case-insensitive search.
◉ -n: displays the lines containing the pattern along with the line numbers.
◉ -v: displays the lines not containing the specified pattern.
◉ -c: displays the count of the matching patterns.

Examples:

◉ Match all lines that start with ‘hello’. E.g: “hello there”

$ grep “^hello” file1

◉ Match all lines that end with ‘done’. E.g: “well done”

$ grep “done$” file1

◉ Match all lines that contain any of the letters ‘a’, ‘b’, ‘c’, ‘d’ or ‘e’.

$ grep “[a-e]” file1

◉ Match all lines that do not contain a vowel

$ grep “[^aeiou]” file1

◉ Match all lines that start with a digit following zero or more spaces. E.g: “ 1.” or “2.”

$ grep “ *[0-9]” file1

◉ Match all lines that contain the word hello in upper-case or lower-case

$ grep -i “hello”

Friday, 17 August 2018

Grep Command in Unix Shell script

Q) How to use the grep command in unix or linux bash scripts to search for a pattern match?


You might have used the grep command to search for a string in a file on the unix command line. Here we will see how to use the grep command in a bash script.

Grep Command, Unix Shell Script, LPI Certification, LPI Tutorial and Material, LPI Guides

Consider the below file with data

> cat sample_file.txt
linux storage
unix distributed system
linux file server
debian server
fedora backup server

Let see the bash script that prints the lines which contain the word server in it. The bash script code is shown below:

>vi grep_script.sh

#!/bin/bash

WORD=server
INPUT_FILE=sample_file.txt
grep "$WORD" $INPUT_FILE

Now we will execute this script and see what the output is

> bash grep_script.sh

linux file server
debian server
fedora backup server

Grep Command, Unix Shell Script, LPI Certification, LPI Tutorial and Material, LPI Guides
Here in the script we have hardcoded the filename and the search pattern. We will see how to pass these as arguments from the command line to the script. The bash script is:

>vi grep_script_command_line.sh

#!/bin/bash

INPUT_FILE=$1
WORD=$2
grep "$WORD" $INPUT_FILE

Now run the script as shown below:

> bash grep_script_command_line.sh sample_file.txt server

Saturday, 14 April 2018

Grep Command in Unix and Linux Examples

Grep Command, Unix Command and Linux Command

Grep is the frequently used command in Unix (or Linux). Most of us use grep just for finding the words in a file. The power of grep comes with using its options and regular expressions. You can analyze large sets of log files with the help of grep command.

Grep stands for Global search for Regular Expressions and Print.

The basic syntax of grep command is


grep [options] pattern [list of files]

Let see some practical examples on grep command.

1. Running the last executed grep command

This saves a lot of time if you are executing the same command again and again.

!grep

This displays the last executed grep command and also prints the result set of the command on the terminal.

2. Search for a string in a file

This is the basic usage of grep command. It searches for the given string in the specified file.

grep "Error" logfile.txt

This searches for the string "Error" in the log file and prints all the lines that has the word "Error".

3. Searching for a string in multiple files.

grep "string" file1 file2
grep "string" file_pattern

This is also the basic usage of the grep command. You can manually specify the list of files you want to search or you can specify a file pattern (use regular expressions) to search for.

4. Case insensitive search

The -i option enables to search for a string case insensitively in the give file. It matches the words like "UNIX", "Unix", "unix".

grep -i "UNix" file.txt

5. Specifying the search string as a regular expression pattern.

grep "^[0-9].*" file.txt

This will search for the lines which starts with a number. Regular expressions is huge topic and I am not covering it here. This example is just for providing the usage of regular expressions.

6. Checking for the whole words in a file.

By default, grep matches the given string/pattern even if it found as a substring in a file. The -w option to grep makes it match only the whole words.

grep -w "world" file.txt

7. Displaying the lines before the match.

Some times, if you are searching for an error in a log file; it is always good to know the lines around the error lines to know the cause of the error.

grep -B 2 "Error" file.txt

This will prints the matched lines along with the two lines before the matched lines.

8. Displaying the lines after the match.

grep -A 3 "Error" file.txt

This will display the matched lines along with the three lines after the matched lines.

9. Displaying the lines around the match

grep -C 5 "Error" file.txt

This will display the matched lines and also five lines before and after the matched lines.

10. Searching for a sting in all files recursively

You can search for a string in all the files under the current directory and sub-directories with the help -r option.

grep -r "string" *

11. Inverting the pattern match

You can display the lines that are not matched with the specified search sting pattern using the -v option.

grep -v "string" file.txt

12. Displaying the non-empty lines

You can remove the blank lines using the grep command.

grep -v "^$" file.txt

13. Displaying the count of number of matches.

We can find the number of lines that matches the given string/pattern

grep -c "sting" file.txt

14. Display the file names that matches the pattern.

We can just display the files that contains the given string/pattern.

grep -l "string" *

15. Display the file names that do not contain the pattern.

We can display the files which do not contain the matched string/pattern.

grep -L "string" *

16. Displaying only the matched pattern.

By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option.

grep -o "string" file.txt

17. Displaying the line numbers.

We can make the grep command to display the position of the line which contains the matched string in a file using the -n option

grep -n "string" file.txt

18. Displaying the position of the matched string in the line

The -b option allows the grep command to display the character position of the matched string in a file.

grep -o -b "string" file.txt

19. Matching the lines that start with a string

The ^ regular expression pattern specifies the start of a line. This can be used in grep to match the lines which start with the given string or pattern.

grep "^start" file.txt

20. Matching the lines that end with a string

The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern.

grep "end$" file.txt