Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Select-String add empty lines?

Tags:

powershell

Here is a minimal repro example.

Expected result:

PS C:\> ("a", "b")
a
b
PS C:\> ("a", "b") | Select-String "b"
b
PS C:\>

Actual result:

PS C:\> ("a", "b")
a
b
PS C:\> ("a", "b") | Select-String "b"

b


PS C:\>

As you can see, the second output has one empty line before and two empty lines after the matched lines.

Why does that happen? And what can I do about it?

(Note: This is a minimal example. In my real code, I'm parsing svn status output for uncommitted files and I get the same problem of spurious newlines.)

like image 315
Heinzi Avatar asked Jan 02 '18 10:01

Heinzi


1 Answers

The reason for weird output is that Powershell is all about objects. In this particular case, Select-String returns MatchInfo object(s). Like so,

PS C:\> $o = ("a", "b") | Select-String "b"
PS C:\> $o

b


PS C:\> $o.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    MatchInfo                                System.Object

For extra confusion, explicit call to ToString() doesn't output the line breaks:

PS C:\> $o.ToString()
b
PS C:\>

For a work-around, query MatchInfo's Line property like so,

PS C:\>  ("a", "b") | Select-String "b" | % { $_.Line }
b
PS C:\>

Please see also Keith Hill's answer about similar a question.

like image 169
vonPryz Avatar answered Nov 12 '22 16:11

vonPryz