Michael
Michael

Reputation: 33

Find the last three characters of a string with Powershell

I have a list of files with the complete path in a file and output this with "Get-Content Filename" on the Comandline of Powershell. I now only want to get the last three characters. This does not seem possible with substring. What other option is there on the command line.

Upvotes: 2

Views: 12849

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174515

You can use Substring(), you just need to calculate the start index manually:

$s = "abcdef"
if($s.Length -gt 3){
  $s.Substring($s.Length - 3) # returns "def"
} else {
  $s
}

You can also use the -replace regex operator to remove anything preceding the last three characters:

$s -replace '^.*(?=.{3}$)'

Here we don't need the length check, -replace will simply not alter the string if the pattern doesn't match anything.

-replace also works on enumerable input, so if you want to apply the operation to every line in the file, it's as simply as:

(Get-Content $filename) -replace '^.*(?=.{3}$)'

The pattern used with replace describes:

^          # Match start of string
.*         # Match any number of any character
(?=.{3}$)  # Pattern MUST be followed by 3 characters and the end of the string

Upvotes: 5

Related Questions