1

Is there an easier way to duplicate the last three characters in a filename in Powershell? I have been using the following codes

To copy the entire name:

dir | Rename-Item -NewName {$_.basename +$_.basename + $_.extension}

To remove the unwanted characters:

Get-ChildItem  -Recurse | 
foreach { $_ | rename-item -newname ($_.Name -replace '(.{15})..(.+)','$1$2')  }

But was hoping for a less time consuming method?

Edit: I want to repeat the last three characters; e.g.:

before:

00469-101236-01-V-3-20-001

after:

00469-101236-01-V-3-20-001 001
mklement0
  • 382,024
  • 64
  • 607
  • 775

1 Answers1

4

The -replace operator offers several placeholders to refer to what the regex matched in the substitution operand; $& refers to the entirety of the match[1], and can be used here:

PS> '00469-101236-01-V-3-20-001' -replace '...$', '$& $&'
00469-101236-01-V-3-20-001 001

Instead of '...$', you could also do '.{3}$'
Note that $& expands to '001', i.e. the last 3 chars. The reason that the start of the filename - everything before the last 3 chars., '00469-101236-01-V-3-20-' - is also present is that -replace only replaces the matching part of the input string.

In the context of your command:

Get-ChildItem -Recurse | Rename-Item -NewName { 
  ($_.BaseName -replace '...$', '$& $&') + $_.Extension 
} -Whatif

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.


[1] You can alternatively use $0 instead of $&, even though only $& is directly documented; $0 is modeled on $<n>, where <n> refers to the index of a capture group inside the regex ((...)), starting with 1 ($1).
That $0 works like $& can be inferred from the documentation of the underlying Regex type: "If the regular expression engine can find a match, the first element of the GroupCollection object (the element at index 0) returned by the Groups property contains a string that matches the entire regular expression pattern" - thanks, marsze.
This helpful regex documentation site contrasts the behavior of various regex engines.

mklement0
  • 382,024
  • 64
  • 607
  • 775