Powershellv2 - remove the last characters from a string

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

eg. 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 received:

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

This eliminates the text at the beginning of the line, but I don’t see how to get rid of the text from the end.

I tried:

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

but they did not work

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

+5
source share
3 answers

If you understand correctly, you need this:

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

Although this does not work exactly with the example you gave, it will give you a variable middle section, that is, starting with 57 characters from the beginning and end of 37 characters from the end.

+6
source

to remove the last x characters in the text, use:

 $text -replace ".{x}$" 

t

 PS>$text= "this is a number 1234" PS>$text -replace ".{5}$" #drop last 5 chars this is a number 
+18
source

Here's how to remove the last 37 characters from your string:

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

but arco's answer is the preferred solution to your common problem.

+1
source

Source: https://habr.com/ru/post/1207827/


All Articles