Home > Software engineering >  Powershell replace year regex
Powershell replace year regex

Time:11-14

I am trying to replace all the file names in the folder that have the year different than 2021.

Example:

some_random_text_20240102 --> some_random_text_20210102 
some_random_text_20220320 --> some_random_text_20210102 
some_random_text_20241020 --> some_random_text_20210102

The only digits are at the end of the file's name. The year represents the first 4. I can't figure out how to add this to the logic (haven't done regex before)

Get-ChildItem -Path "." -Filter "*.csv" | Rename-Item -NewName { $.BaseName.Replace("20[0-9][0-9]","2021") $.Extension }

CodePudding user response:

You can use

Get-ChildItem -Path ".\" -Filter "*.csv" | `
   Rename-Item -NewName { $_.Name -replace '(?<=_)(?!2021)\d{4}(?=\d{4}\.csv$)', '2021' }

See the regex demo.

Details:

  • (?<=_) - a location that is immediately preceded with a _ char
  • (?!2021) - the next four chars on the right cannot be a 2021 string
  • \d{4} - any four digits
  • (?=\d{4}\.csv$) - immediately after the four digits, there must be another four digits, and then .csv that should be at the end of string.
  • Related