3

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 ''
}
SeanBateman
  • 31
  • 1
  • 1
  • 3
  • 1
    How are you defining `$Texfile`? (`Get-content xxx`, `Get-Content xxx -raw`, or something else?) And did you have a typo and mean `$Textfile`? – BenH May 22 '17 at 20:42
  • If you curious *why* `-8..-1` doesn't produce expected result: https://stackoverflow.com/a/28461189/4424236 – beatcracker May 22 '17 at 20:50
  • 2
    @beatcracker The post you linked is not relevant. You can use negative indexes on strings and character arrays. For example try `'1234'[-3..-1]` In the SeanBateman's question, `-8..-1` interpolates into `-8,-7,-6,-5,-4,-3,-2,-1` each of which is a valid index (assuming the line long enough). The question you linked is an issue using both a positive start and a negative end. – BenH May 22 '17 at 21:04
  • 1
    The code you posted should normally do what you want. Please provide sample input and show how you read that input, so we can reproduce the problem. – Ansgar Wiechers May 22 '17 at 21:31
  • @BenH Woe unto me! I'll leave my original comment as-is, to be eternally reminded that just glancing over the question is not enough. – beatcracker May 23 '17 at 00:00

3 Answers3

2

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)
}
tommymaynard
  • 1,981
  • 12
  • 14
  • 3
    The problem with using the `Substring()` method is that it will throw an error if the string is shorter than 8 characters. The index operater is a safer approach. – Ansgar Wiechers May 22 '17 at 21:29
  • this one threw super-weird errors for me under different conditions. Moved to the other other option. like was throwing nulls with longer names and such. Worked some times, not others. – mbourgon Apr 09 '21 at 12:49
2

Try this:

foreach ($Line in $Texfile) {
  $Line.Remove(0, ($Line.Length - 8))
}
Fabian Mendez
  • 512
  • 5
  • 15
-1

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
js2010
  • 23,033
  • 6
  • 64
  • 66