$ grep --help | grep -i contextContext control:-B, --before-context=NUM print NUM lines of leading context-A, --after-context=NUM print NUM lines of trailing context-C, --context=NUM print NUM lines of output context-NUM same as --context=NUM
-A 5 # this will give you 5 lines after searched string.-B 5 # this will give you 5 lines before searched string.-C 5 # this will give you 5 lines before & after searched string
<强>例子。File.txt包含6行,以下是操作。
[abc@xyz]~/% cat file.txt # print all file datathis is first linethis is 2nd linethis is 3rd linethis is 4th linethis is 5th linethis is 6th line
[abc@xyz]~% grep "3rd" file.txt # we are searching for keyword '3rd' in the filethis is 3rd line
[abc@xyz]~% grep -A 2 "3rd" file.txt # print 2 lines after finding the searched stringthis is 3rd linethis is 4th linethis is 5th line
[abc@xyz]~% grep -B 2 "3rd" file.txt # Print 2 lines before the search string.this is first linethis is 2nd linethis is 3rd line
[abc@xyz]~% grep -C 2 "3rd" file.txt # print 2 line before and 2 line after the searched stringthis is first linethis is 2nd linethis is 3rd linethis is 4th linethis is 5th line