Search code examples
regexpowershellrenamefile-renamebatch-rename

Error with Powershell add suffix to filenames based on prefix


So I have a list of files in a folder in jpg format like so:

"1.George ABCD.jpg"
"2.George ABCD.jpg"
"3.Mead ABCD.jpg"

So what I want to do is rename them so that the the prefix becomes a suffix like so:

"George ABCD 1.jpg"
"George ABCD 2.jpg"
"Mead ABCD 2.jpg"

and I want to have it work recursively through sub folders.

I have a code segment that I've tried that works here:

ls -Recurse |? BaseName -match '^(\d+\.)([^0-9].*)$' |ren -new {"{0}{1}{2}" -f $matches[2],' ', $matches[1].substring(0,1)+ $_.extension}
cmd /c pause

Now the problem is my piece of code currently doesn't work for double digit names for example:

"11.George ABCD.jpg"

Instead what it does is it spits out

"George ABCD 1.jpg"

which is not what I want, I know it's something to do with the regular expression d+ which is one or more digits, but I'm not sure what I should use instead to make it work properly for one or more digit numbers.

That is I want the output for "11.George ABCD.jpg" to be "George ABCD 11.jpg".

Is there any way I can fix this?


Solution

  • It is because of $matches[1].substring(0,1). You are always only using the first digit of your match. You can get what you want by modifying your first group in your regex and not using substring later:

    ls -Recurse |? BaseName -match '^(\d+)\.([^0-9].*)$' |ren -new {"{0}{1}{2}" -f $matches[2],' ', $matches[1] + $_.extension}