1

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)

2
  • You might need a -match operator to get the first match only. Or -replace: -replace '^(\d).*', '$1' Commented Aug 28, 2019 at 19:31
  • hm, but how exactly do I apply -match or -replace operators in a pipeline? for example, after I get the last string of a file. Commented Aug 28, 2019 at 19:42

2 Answers 2

1

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].

Sign up to request clarification or add additional context in comments.

1 Comment

I like the parentheses solution. Thanks
0

It looks like a csv to me...

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

output:

n

1 Comment

a good one, but this particular file may look like a csv file but it not necessarily should be it, so I decided to get more general solution for different data structures with one common feature -- line number at the beginning of each line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.