Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershellv2 - remove last x characters from a string

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?

like image 363
IGGt Avatar asked Nov 27 '14 16:11

IGGt


People also ask

How do I remove last 4 characters from a string in PowerShell?

Using the remove() method in PowerShell, you can remove the last character from the string. We can delete the last character from the string using both remove() methods available.

How do I remove the last character of a string in PowerShell?

Result is “DCCOMP01″. This works especially well when the last character is a special PowerShell reserved one like “$”.

How do I remove the first character of a string in PowerShell?

Substring(1) returns a substring containing all chars after the first one. Show activity on this post. You can remove the first character with the -replace operator: (Get-User $_ | select -Expand sAMAccountName) -replace '^.

How do you split a string in PowerShell?

UNARY and BINARY SPLIT OPERATORS Use one of the following patterns to split more than one string: Use the binary split operator (<string[]> -split <delimiter>) Enclose all the strings in parentheses. Store the strings in a variable then submit the variable to the split operator.


2 Answers

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
like image 71
Rudolph Avatar answered Sep 28 '22 03:09

Rudolph


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

like image 37
arco444 Avatar answered Sep 28 '22 03:09

arco444