Reputation: 41
I'm trying to get the last 8 characters of every line of an array in the pipeline, I thought this would output the last 8 characters but the output seems to be blank
foreach($line in $Texfile)
{
$line[-8..-1]-join ''
}
Upvotes: 4
Views: 60520
Reputation: 27606
That works fine. You misspelled $textfile though, with no "t". Maybe that's why you had no output.
Or (-join on the left side):
'1234567890
1234567890
1234567890' | set-content file
$textfile = cat file
foreach($line in $textfile)
{
-join $line[-8..-1]
}
34567890
34567890
34567890
Upvotes: -1
Reputation: 532
Try this:
foreach ($Line in $Texfile) {
$Line.Remove(0, ($Line.Length - 8))
}
Upvotes: 3
Reputation: 2152
There's any number of ways to do this, but I opted to pipe Get-Content to ForEach-Object.
Get-Content -Path <Path\to\file.txt> | ForEach-Object {
$_.Substring($_.Length - 8)
}
In your example, you'd use $Line in place of $_ and not pipe to ForEach-Object, and instead, use the Foreach language construct as you've done.
Foreach ($Line in $TextFile) {
$Line.Substring($Line.Length - 8)
}
Upvotes: 2