3

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?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Patata Pequeña
  • 115
  • 1
  • 11
  • You can install `gnu awk` for windows. I do not think you can get a simple solution for `grep -B` using built in windows function. – Jotne Mar 20 '14 at 14:07
  • possible duplicate of [What are good grep tools for Windows?](http://stackoverflow.com/questions/87350/what-are-good-grep-tools-for-windows) – fedorqui Jan 15 '15 at 14:15
  • [Grep with context about matched lines in Windows](http://superuser.com/q/689886/241386) – phuclv Feb 22 '17 at 16:50

1 Answers1

3

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

mikemaccana
  • 110,530
  • 99
  • 389
  • 494