Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows equivalent to grep -B (before context) and -A (after context)?

In grep I understand there is a -B switch that will...

Print NUM lines of leading context before matching lines.

... so for example you might run a command like:

cvs log -N -S -w<userid> -d"1 day ago" | grep -B14 "some text" > afile

Is there an equivalent to this in Windows? What I've currently got is:

cvs log -N -S -w<userid> -d"1 day ago" | find "7492" > output.txt

But this only pipes the text on the same line as 7492 in the output, whereas I need some of the preceding lines to usefully interpret the information. But as far as I can see the find command doesn't have a switch equivalent to the -B switch of grep. Is there some way of replicating this aspect of grep functionality in Windows?

like image 887
Patata Pequeña Avatar asked Feb 02 '26 15:02

Patata Pequeña


1 Answers

Use select-string's -context argument. Example:

git log | select-string limit -context 5,0

This is for 5 line before, 0 lines after. This example happens to get the hash that matches a git commit message.

If you enter one number as the value of this parameter, that number determines the number of lines captured before and after the match. If you enter two numbers as the value, the first number determines the number of lines before the match and the second number determines the number of lines after the match.

See MSDN docs for select-string

like image 54
mikemaccana Avatar answered Feb 05 '26 07:02

mikemaccana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!