Иногда требуется выполнить поиск вхождения + несколько строк перед/после совпадения.
Для этого в grep предусмотрено несколько опций.
Для примера возьмём такой файл:
$ cat file.txt 11111 22222 33333 44444 55555 66666
В man grep имеются слеюдующие опции:
Context Line Control
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.
-C NUM, -NUM, --context=NUM
Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.
Примеры работы.
-A (after — после):
$ cat file.txt | grep 3 -A 2 33333 44444 55555
-B (before — перед):
$ cat file.txt | grep 3 -B 2 11111 22222 33333
-C (conext — контекст, до и после):
$ cat file.txt | grep 3 -C 2 11111 22222 33333 44444 55555
-A и -B можно совмещать:
$ cat file.txt | grep 3 -A 1 -B 2 11111 22222 33333 44444




