Rename file name with Regex and get rid of everything after with powershell

Viewed 141

Hi I'm trying to rename file names with regex and powershell. I got it to replace certain files with the following code but i want to do this for everything after the _underscore. I got over a hundred files i need to rename.

get-childitem *.pdf | foreach { rename-item $_ $_.Name.Replace("_R12B", "") }

Here are example files i'm trying to change;

YTER-01-0B-B-PD-00003-2_R12B

YTER-01-0A-B-PZ-00001-2_R9B

YTER-01-0U-B-PG-00003-1_R1B

YTER-01-0G-B-PP-00005-1_R4B

1 Answers

You may use

get-childitem *.pdf | foreach { rename-item $_ ($_.Name -replace '_[^_]+(?=\.pdf$)') }

The _[^_]+(?=\.pdf$) regex matches

  • _ - an underscore
  • [^_]+ - 1+ chars other than an underscore
  • (?=\.pdf$) - followed with .pdf at the end of string.

See the regex demo.

Related