PowerShell Select-String in Context: Lines Before & After Match

Select-String in Context using Windows PowerShell

The grep command in Linux is widely used to search for patterns in files and show surrounding lines using flags like -A, -B, or -C. But when switching to Windows PowerShell, many users struggle to find an equivalent. The PowerShell Select-String command is the answer. To show lines before and/or after a match, use the Select-String command with the -Context parameter. This lets you display a number of lines before, after, or both around the matching line. This guide explains how to use PowerShell Select-String to replicate grep’s context flags.

Cool Tip: Wondering how to grep in Windows? Discover Windows grep command equivalent in CMD and PowerShell! Read more →

Using PowerShell Select-String Context

The Select-String command in PowerShell is the closest match to Linux’s grep. It supports regex, file input, and line filtering. To show lines before and after a match, use the -Context parameter.

ℹ️ The -Context parameter takes two integers: the first for lines before, the second for lines after.

Show N Lines Before Match

To show 3 lines before each match:

PS C:\> Select-String -Pattern "error" -Path "log.txt" -Context 3,0

Show N Lines After Match

To show 2 lines after each match:

Select-String -Pattern "timeout" -Path "log.txt" -Context 0,2

Show Lines Before and After Match

You can adjust the numbers freely:

Select-String -Pattern "disconnect" -Path "log.txt" -Context 5,10

This shows 5 lines before and 10 lines after each match.

Cool Tip: Wondering how to cat in Windows? Discover Windows cat command equivalent in CMD and PowerShell! Read more →

Conclusion

The PowerShell Select-String command is a powerful tool for pattern matching and context display. By using the -Context parameter, you can show lines before match, after match, or both. This allows you to view the match in context.

Was it useful? Share this post with the world!

Leave a Reply