Nick
Nick

Reputation: 191

Rename files with Powershell if file has certain structure

I am trying to rename files in multiple folder with same name structure. I got the following files:

I want to add the following text in front of it: "Subject is missing"

I only want to rename these files all other should remain the same

Upvotes: 1

Views: 744

Answers (1)

mklement0
mklement0

Reputation: 437111

Tip of the hat to LotPings for suggesting the use of a look-ahead assertion in the regex.

Get-ChildItem -File | Rename-Item -NewName { 
  $_.Name -replace '^(?=\(\d+\)\.)', 'Subject is missing '
} -WhatIf

-WhatIf previews the renaming operation; remove it to perform actual renaming.

  • Get-ChildItem -File enumerates files only, but without a name filter - while you could try to apply a wildcard-based filter up front - e.g., -Filter '([0-9]).*' - you couldn't ensure that multi-digit names (e.g., (13).txt) are properly matched.

    • You can, however, pre-filter the results, with -Filter '(*).*'
  • The Rename-Item call uses a delay-bind script block to derive the new name.

    • It takes advantage of the fact that (a) -rename returns the input string unmodified if the regex doesn't match, (b) Rename-Item does nothing if the new filename is the same as the old.
  • In the regex passed to -replace, the positive look-ahead assertion (?=...) (which is matched at the start of the input string (^)) looks for a match for subexpression \(\d+\)\. without considering what it matches a part of what should be replaced. In effect, only the start position (^) of an input string is matched and "replaced".

    • Subexpression \(\d+\)\. matches a literal ( (escaped as \(), followed by 1 or more (+) digits (\d), followed by a literal ) and a literal . (\.), which marks the start of the filename extension. (Replace .\ with $, the end-of-input assertion if you want to match filenames that have no extension).
  • Therefore, replacement operand 'Subject is missing ' is effectively prepended to the input string so that, e.g., (1).txt returns Subject is missing (1).txt.

Upvotes: 1

Related Questions