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?
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.
Result is “DCCOMP01″. This works especially well when the last character is a special PowerShell reserved one like “$”.
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 '^.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With