Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting last X characters from each line PowerShell

Tags:

powershell

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 ''
}
like image 780
SeanBateman Avatar asked Oct 14 '25 16:10

SeanBateman


2 Answers

Try this:

foreach ($Line in $Texfile) {
  $Line.Remove(0, ($Line.Length - 8))
}
like image 170
Fabian Mendez Avatar answered Oct 17 '25 10:10

Fabian Mendez


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)
}
like image 42
tommymaynard Avatar answered Oct 17 '25 08:10

tommymaynard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!