21

I have a file containing a few thousand lines of text. I need to extract some data from it, but the data I need is always 57 characters from the left, and 37 characters from the end. The bit I need (in the middle) is of varying length.

e.g. 20141126_this_piece_of_text_needs_to_be_removed<b>this_needs_to_be_kept</b>this_also_needs_to_be_removed

So far I have got:

SELECT-STRING -path path_to_logfile.log -pattern "20141126.*<b>" | 
FOREACH{$_.Line} | 
FOREACH{
    $_.substring(57)
    }

This gets rid of the text at the start of the line, but I can't see how to get rid of the text from the end.

I tried:

$_.subString(0,-37)
$_.subString(-37)

but these didn't work

Is there a way to get rid of the last x characters?

IGGt
  • 2,627
  • 10
  • 42
  • 63

3 Answers3

54

to remove the last x chars in a text, use:

$text -replace ".{x}$"

ie

PS>$text= "this is a number 1234"
PS>$text -replace ".{5}$" #drop last 5 chars
this is a number
freshbm
  • 5,540
  • 5
  • 46
  • 75
Rudolph
  • 541
  • 1
  • 4
  • 2
14

If I understand you correctly, you need this:

$_.substring(57,$_.length-57-37)

Though this doesn't seem to work precisely with the example you gave but it will give you the varying middle section i.e. starting at 57 chars from the start and ending 37 chars from the end

arco444
  • 22,002
  • 12
  • 63
  • 67
6

This is how to remove the last 37 characters from your string:

$_.subString(0,$_.length-37)

but arco´s answer is the preferred solution to your overall problem

Paul
  • 5,524
  • 1
  • 22
  • 39