elcool
elcool

Reputation: 6141

Split pattern output by spaces in Powershell

I need to extract the third column of a string returned after matching a Pattern. It also needs to be a one-liner

File contains data like this:

f5834eab44ff bfd0bc8498d8 1557718920
dc8087c38a0d a72e89879030 1557691221
e6d7aaf6d76b caf6cd0ef68c 1557543565

Right now it matches the pattern and returns the line. But I cannot get it to Split on the spaces so I can get the 3rd column (index 2).

    select-string -Path $hashlistfile -Pattern 'dc8087c38a0d') | $_.Split(" ") | $_[2] 

Output should be:

1557691221

Upvotes: 0

Views: 185

Answers (2)

js2010
js2010

Reputation: 27428

You can only use '$_' inside cmdlets that have a script block option '{ }'. Select-string returns MatchInfo objects.

(select-string dc8087c38a0d $hashlistfile).gettype()

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

The -split operator seems to deal with it more easily. There's an extra parenthesis ')' after the pattern in your example.

select-string dc8087c38a0d $hashlistfile | foreach { -split $_ | select -index 2 }

1557691221

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

You can grab the Line property from the output object produced by Select-String, split that and then index directly into the result of String.Split():

Select-String -Path $hashlistfile -Pattern dc8087c38a0d |ForEach-Object {
  $_.Line.Split(" ")[2]
}

Upvotes: 2

Related Questions