Cutting Off Text at the End

by Dec 25, 2012

Cutting off a part of a text at its beginning is easy. This line eats the first 3 characters:

PS> 'C:\folder\file.txt'.SubString(3)
folder\file.txt

Cutting off text at its end is not so easy because there is no method for it. You would always have to refer to the total text length which requires you to store it in a variable:

$text = 'C:\folder\file.txt'
$text.Remove($text.Length - 4)
C:\folder\file

Regular expressions can help. Use -replace and omit the replacement text to cut it off:

'C:\folder\file.txt' -replace '.{4}$'
C:\folder\file

The regular expression told PowerShell to search for "anything" (".") four times ({4}) at the end of a text ($). And the next expression will always cut off a file extension, no matter how long it is:

'C:\folder\file.ps1xml' -replace '\..*?$'
C:\folder\file

It looks for a real dot (\.), then anything (.) as many times as necessary (*?) to reach the text end ($).

Twitter This Tip! ReTweet this Tip!