How to print lines matching pattern or string ?


Consider you have a file called dictionary.txt with a huge collection of words and you only want to view line containing the word "tux". To check each word line by line is a tedious task, instead we use the grep command.

grep command searches line by line for a string or a pattern in a file containing plain-text data and displays the results. This is one of the most powerful and most used Linux commands.The syntax for using grep is
grep [option] pattern filename
grep [option] pattern /path/to/file

Example
grep tux /usr/share/dict/words
will check for lines containing the word "tux" inside the dictionary word file /usr/share/dict/words
and display the result
Patuxent
tux
tuxedo
tuxedoed
tuxedoes
tuxedos
tuxes

Some important options:


-i  : Ignores case sensitivity in both pattern and input file.

-v : Displays lines not containing the pattern.

-c :  Prints the count of matching lines instead of the normal output.

-n :  Prefix each line of output with line number within its input file.

-r :  Read  all files under each directory, recursively.

-x : Performs only exact line matches

--color : Matching patterns displayed colorfully.


egrep and fgrep

egrep and fgrep are two variants of the grep command.  egrep is the same as grep -E, which  Interpret pattern as an extended regular expression. Similarly  fgrep is the same as grep -F and the pattern is interpreted as a list of fixed strings, separated by newlines, any of which is to be matched.

Comments

Popular posts from this blog

Understanding awk command with examples

what is an inode?

Understanding sed command with example -Part 1