Ivan
Ivan

Reputation: 163

How to address "Select-String -pattern" return object via pipeline without using foreach loop?

Let's say I have a file with a following content:

1,first_string,somevalue
2,second_string,someothervalue
n,n_nd_string,somemorevalue

I need to Get-Content of this file, get the last string and get the number before the "," symbol (n in this case). (I'll just increment it and append n+1 string to this file, but it does not matter right now). I want all this stuff be done with pipeline cascade

I have come to this solution so far:

[int]$number = Get-Content .\1.mpcpl | Select-Object -Last 1 | Select-String -Pattern '^(\d)' | ForEach-Object {$_.matches.value}

It actually works, but I wonder if there are any ways of addressing Select-String -Pattern '^(\d)' return object without using the foreach loop? Beacause I know that the return collection in my case will only consist of a 1 element (I'm selecting a single last string of a file and I get only one match)

Upvotes: 1

Views: 129

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626853

You may use

$num = [int]((Get-Content .\1.mpcpl | Select-Object -Last 1) -replace '^(\d).*', '$1')

Notes

  • (Get-Content .\1.mpcpl | Select-Object -Last 1) - reads the file and gets the last line
  • (... -replace '^(\d).*', '$1') - gets the first digit from the returned line (NOTE: if the line does not start with a digit, it will fail as the output will be the whole line)
  • [int] casts the string value to an int.

Another way can be getting a match and then retrieving it from the default $matches variable:

[IO.File]::ReadAllText($filepath) -match '(?m)^(\d).*\z' | Out-Null
[int]$matches[1]

The (?m)^(\d).*\z pattern gets the digit at the start of the last line into Group 1, hence $matches[1].

Upvotes: 1

js2010
js2010

Reputation: 27433

It looks like a csv to me...

import-csv 1.mpcpl -header field1,field2,field3 | select -last 1 | select -expand field1

output:

n

Upvotes: 0

Related Questions