Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell: remove text from end of string

Tags:

powershell

--deleted earlier text - I asked the wrong question!

ahem....

What I have is $var = "\\unknowntext1\alwaysSame\unknowntext2"

I need to keep only "\\unknowntext1"

like image 729
AshClarke Avatar asked Apr 29 '11 11:04

AshClarke


1 Answers

Try regular expressions:

$foo = 'something_of_unknown' -replace 'something.*','something'

Or if you know only partially the 'something', then e.g.

'something_of_unknown' -replace '(some[^_]*).*','$1'
'some_of_unknown' -replace '(some[^_]*).*','$1'
'somewhatever_of_unknown' -replace '(some[^_]*).*','$1'

The $1 is reference to group in parenthesis (the (some[^_]*) part).

Edit (after changed question):

If you use regex, then special characters need to be escaped:

"\\unknowntext1\alwaysSame\unknowntext2" -replace '\\\\unknowntext1.*', '\\unknowntext1'

or (another regex magic) use lookbehind like this:

"\\unknowntext1\alwaysSame\unknowntext2" -replace '(?<=\\\\unknowntext1).*', ''

(which is: take anything (.*), but there must be \\unknowntext1 before it ('(?<=\\\\unknowntext1)) and replace it with empty string.

Edit (last)

If you know that there is something known in the middle (the alwaysSame), this might help:

"\\unknowntext1\alwaysSame\unknowntext2" -replace '(.*?)\\alwaysSame.*', '$1'
like image 59
stej Avatar answered Sep 28 '22 18:09

stej