1

I need to keep the first 5 characters from data being pulled from a text file.

Data looks like this:

S1831KWT0081
S2004KWT0083
S2351KWT0085
S0054KWT0087

Results should looks like this:

S1831
S2004
S2351
S0054

I can get it working when setting the variable within PowerShell:

PS> $a = "S1831KWT0081"
PS> $a.Substring(0, $a.IndexOf('K'))

S1831

but I'm stuck when trying to pull from a text file.

5
  • > But I'm stuck when trying to pull from a text file. How so? Could you give some examples of what you have tried? The only code you've given is what you've gotten to work. Commented Jul 10, 2017 at 14:18
  • $location = Get-Content "C:\location.txt" $location.Substring(0, $location.IndexOf('K')) Commented Jul 10, 2017 at 14:24
  • 1
    $location = Get-Content "C:\location.txt" | ForEach-Object { $_.Substring(0, $_.IndexOf('K')) } Commented Jul 10, 2017 at 14:27
  • This actually exposes the issue you're having - in your question, you treat each line as a separate entity. In your comment, you basically treat an entire array as a variable. :) Commented Jul 10, 2017 at 14:27
  • Amazing how easy it is once you see the solution. Thanks guys! Commented Jul 10, 2017 at 14:32

3 Answers 3

1

To solve this, you will need to parse the text file on a line-by-line basis. Basically treating each line as a value in an array.

Get-Content location.txt | foreach { $_.Substring(0, $_.IndexOf('K')) }
Sign up to request clarification or add additional context in comments.

Comments

1

Another option would be a regular expression replacement:

(Get-Content 'C:\path\to\input.txt') -replace '^(.{5}).*', '$1'

That would also allow you more specific matches, e.g. like this:

$re = '^([a-z]\d{4}).*'
(Get-Content 'C:\path\to\input.txt') -match $re -replace $re, '$1'

Comments

0

Just to show there always is more than one PoSh way ;-)

gc .\input.txt|%{$_.split('K')[0]}

Or the more verbose version

Get-Content .\input.txt | 
  ForEach-Object { $_.split('K')[0] }

Comments

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.