Wednesday, May 13, 2015

Grep - before and after

The grep is a command line utility for searching plain-text data sets for lines matching the given regular expression. And those using Linux (or some or other flavor of this OS), must have used this command. Here are two useful options of this command: -A for After and -B for Before. Both take a number as their value.

As their names suggest, -A gives you matching line and N lines after the matching line, similarly, -B gives you matching line and N lines before the matching line.

You can also combine both these options into single command. And, if your -A and -B values are same, then you can simply use -C option. C stands for Count.

# to get matching line and 5 lines before that
grep -B 5 "pattern" file
# to get matching line and 5 lines after that
grep -A 5 "pattern" file
# of course, you can combine -A and -B options together in single command. That's obvious.
# if your -A and -B values are same, you need not specify both the options. use -C instead.
grep -C 5 "pattern" file

No comments:

Post a Comment