Most Commonly used "grep" commands...

Some history of grep command before moving to its practical use:

  • Grep is a command line utility used in Unix and Linux to find/search text.
  • Grep stands for "g/re/p" ↔ globally search a regular expression and print stands
  • Grep was originally developed only for UNIX OS. However, later it was available for other OS which are similar to UNIX.
  • Grep was created overnight by Ken Thompson to help him analyze text while fixing some bug which had large amount of text.
  • Grep was first included in Unix version 4.
  • Early variants of grep included 'egrep' and 'fgrep

Lets dive in to its basic uses:

  1. Syntax : To search single string in single file. ↠  grep "string" filename
  2. Syntax : To search single string in multiple files. ↠ grep "string" filename*
  3. Syntax : To search case insensitive string ↠ grep -i "string" filename
NOTE: While searching string in multiple files, we need to provide only common characters from filename before putting '*' ; this will make sure all files containing those common character in names are searched.

Other Uses of Grep Command :

  1. To use grep recursively ↠ grep -r "string" filename
  2. To suppress output (filename) ↠ grep -hR "string" filename
  3. To search invert using grep ↠ grep -v "string" filename
  4. To use grep with shell pipe ↠ dmesg | egrep "string" 
  5. To use grep with cat command ↠ cat filename | grep 'string'
  6. To count amount of string in file using grep ↠ grep -c "string" filename
grep command options
Description
-i
Ignore case sensitivity
-w
To match exact string
-v
Select invert lines from file
-n
Print line number with output
-h
Suppress the file name prefix in output
-r
Search directories recursively
-l
Print only names of file with selected lines
-c
Print only a count of selected lines per FILE

No comments:

Post a Comment