1

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 }

1 Answer 1

0

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.