How to Select-String multiline?

vanillacoke9191 picture vanillacoke9191 · Mar 27, 2019 · Viewed 8.7k times · Source

I am trying to Select-String on a text that is on multiple lines.

Example:

 "This is line1
 <Test>Testing Line 2</Test>
 <Test>Testing Line 3</Test>"

I want to be able to select all 3 lines in Select-String. However, it is only selecting the first line when I do Select-String -Pattern "Line1". How can I extract all 3 lines together?

Select-String -Pattern "Line1"

Answer

mklement0 picture mklement0 · Mar 27, 2019

Select-String operates on its input objects individually, and if you either pass a file path directly to it (via -Path or -LiteralPath) or you pipe output from Get-Content, matching is performed on each line.

Therefore, pass your input as a single, multiline string, which, if it comes from a file, is most easily achieved with Get-Content -Raw (PSv3+):

Get-Content -Raw file.txt | Select-String -Pattern Line1

Note that this means that if the pattern matches, the file's entire content is output, accessible via the output object's .Line property.


By contrast, if you want to retain per-line matching but also capture a fixed number of surrounding lines, use the -Context parameter.

Get-Content file.txt | Select-String -Pattern Line1 -Context 0, 2

Ansgar Wiechers' helpful answer shows how to extract all the lines from the result.