grep linux command

_stdin stdout -file --opt --help --version_

grep [options] pattern [files]

The grep command is one of the most consistently useful and powerful in the Linux arsenal. Its premise is simple: given one or more files, print all lines in those files that match a particular regular expression pattern. For example, if a file randomlines contains these lines:

_The quick brown fox jumped over the lazy dogs! My very eager mother just served us nine pancakes. Film at eleven._

and we search for all lines containing “pancake”, we get:

→ grep pancake randomlines
_My very eager mother just served us nine pancakes._ Now we use a regular expression to match lines ending in an exclamation point:
→ grep '\!$' randomlines
_The quick brown fox jumped over the lazy dogs!_

grep can use two different types of regular expressions, which it calls basic and extended. They are equally powerful, just different, and you may prefer one over the other based on your experience with other grep implementations. The basic syntax is in Table 2. Regular expressions are well worth your time to learn. Other powerful Linux programs use them as well, such as sed and perl.

-v _Print only lines that do not match the regular expression._

-l _Print only the names of files that contain matching lines, not the lines themselves._

-L _Print only the names of files that do not contain matching lines._

-c _Print only a count of matching lines._

-n _In front of each line of matching output, print its original line number._

-b _In front of each line of matching output, print the byte offset of the line in the input file._

-i _Case-insensitive match._

-w _Match only complete words (i.e., words that match the entire regular expression)._

-x _Match only complete lines (i.e., lines that match the entire regular expression). Overrides -w._

-A N _After each matching line, print the next N lines from its file._

-B N _Before each matching line, print the previous N lines from its file._

-C N _Same as -A N -B

N print N lines (from the original file) above and below each matching line._

--color=always _Highlight the matched text in color, for better readability._

-r _Recursively search all files in a directory and its subdirectories._

-E _Use extended regular expressions. See egrep._

-F _Use lists of fixed strings instead of regular expressions. See fgrep._

[src: Linux Pocket Guide 3rd Edition]
Join our telegram channel
Back to home page

Comments