We earn commission when you buy through affiliate links.

This does not influence our reviews or recommendations.Learn more.

Its often used to filter out unnecessary details while printing just the required information from big log files.

The power ofregular expressioncombines with supported options in grep makes this possible.

Here we will be covering some of the commonly used grep command in different scenarios bysysadminor developer.

Heres how it’s possible for you to look for a pattern in multiple files by using*wildcard.

grep offers to search a pattern without looking at the case of the pattern.

Use-iflag to tell grep to ignore case.

you might do that with-wflag.

We can get this count using-coption.

grep allows you to easily do that with-rflag.

With-v, whichever lines dont match the pattern gets printed.

Use-noption as shown to get line numbers in output.

Limit grep Output

For big files likes logs etc.

We can use m[num]to limit the printed lines by num.

Herenumdenotes the number of additional lines to be printed which is just above or below the matched line.

This is applicable to all matches that grep finds in the specified file or file list.

OR

Below output shows a normal grep output as well as output with flag-A,-Band-Cone by one.

Notice how grep interprets the flags and their values and the changes in respective output.

With-A1flag, grep prints 1 line which follows just after the matching line.

Similarly, with-B1flag, it prints 1 line just before the matching line.

With-C1flag, it prints 1 line which is before and after the matching line.

grep allows-xflag to do just that.

Heres how to do it.

Enclosing in quotes can help when the pattern contains spaces etc.

Match Ending String

Another common useful regular expression is to match the end of the line pattern.

We tried to match a.character at the end of the line.

Since dot (.)

is a special meaning character, we need to escape it with\character.

(not the ones that may contain it anywhere in between).

The file should contain one pattern per line.

In our example, weve created pattern file namespattern.txtwith the below contents:

To use it, use-fflag.

Specify Multiple Patterns

grep allows specifying multiple patterns using-eflag.

Specify Extended RegEx

grep also supports Extended Regular Expressions or ERE using-Eflag.

This is similar toegrepcommand in Linux.

That being said, using-Ewith grep is equivalent toegrepcommand.

Heres one use of ERE where we want to print lines that are not commented or blank.

This is especially useful for finding something in big configuration files.

Ive additionally used-vflag to NOT print lines matching the pattern'^(#|$)'.

Conclusion

The above examples are just the tip of the iceberg.

Refer to its man page to read more about it.

Next, learnSFTP command examples.