Monday, May 07, 2018

grep command in Unix

grep (globally search for regular expression and print out) command in Unix/Linux

The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern.

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.



 1. Case insensitive search : The -i option enables to search for a string case insensitively in the give file.   It Can matches the words like “SHOBHIT”, “Shobhit”, “shobhit”, "ShoBhit"
 
$grep -i "ShoBhit" Demofile.txt

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

$grep -c "Shobhit" Demofile.txt

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

$grep -l "Shobhit" *

or
 
$grep -l "Shobhit" Demofile1.txt Demofile2.txt Demofile3.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 "Shobhit" Demofile.txt

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

$ grep -n "Shobhit" Demofile.txt

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

$ grep -v "Shobhit" Demofile.txt

7. 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 "^Shobhit" Demofile.txt

8.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 "hit$" Demofile.txt

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

$grep –e "Shobhit" –e "Sobhit" –e "Shobit" Demofile.txt

No comments:

Post a Comment

Clear BNE Cache for WebADI Changes

It Sometime happens that WebAdi Changes doesn't reflect once migrated in controlled instances. Here are the quick steps(Generally perfor...