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)

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)

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

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

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 '\..*?$'

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

Twitter This Tip! ReTweet this Tip!