HomeTechnologyNewsHow to show surrounding lines around matches with grep for Linux

How to show surrounding lines around matches with grep for Linux

- Advertisement -
- Advertisement -
- Advertisement -
- Advertisement -

[ad_1]

grep is a search utility for finding strings and patterns in files and console input. By default, it prints the line containing the match, but it is also useful to print the previous lines around a match by context.

Print context for grep matches

when you use grepyou can add the capitals -C flag for “context”, which will print N number of lines before and after the match. This can be quite useful for searching through code files, or anything else where you need to read what’s going on around the match.

grep -C 4 "foo" file

This is a fairly common command that you don’t actually need to specify the -C flag if it is between 1 and 9, you can use a flag like -4 for 4 lines of context:

grep -4 "foo" file

If there are multiple matches, grep will display a delimiter between them, except if they are close enough to be in context with each other. When you have multiple matches, it is also useful to display the line numbers with the -n flag so you can see where the match is located in the file.

grep -4 -n "foo" file

You can also manually specify how many lines you want before and after with -B for before and -A for later. Make sure you don’t mix them with “up and down”, because it would be the other way around.

grep -A 1 -B 3 "foo" file

[ad_2]

- Advertisement -
- Advertisement -
Stay Connected
[td_block_social_counter facebook="#" manual_count_facebook="16985" manual_count_twitter="2458" twitter="#" youtube="#" manual_count_youtube="61453" style="style3 td-social-colored" f_counters_font_family="450" f_network_font_family="450" f_network_font_weight="700" f_btn_font_family="450" f_btn_font_weight="700" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjMwIiwiZGlzcGxheSI6IiJ9fQ=="]
Must Read
- Advertisement -
Related News
- Advertisement -