LoTus
LoTus

Reputation: 65

How to append a number to a RegEx region variable in PowerShell?

I have JPEG files in a folder named sequentially: table1.jpg, table2.jpg, table3.jpg, ..., table11.jpg

I need to do some processing on them, in sequential order, but a Get-ChildItem will return this (even with Sort):

table1.jpg
table10.jpg
table11.jpg
table2.jpg
table3.jpg
...

I would like to add a 0 to get them in the correct order:

table01.jpg
table02.jpg
table03.jpg
...
table11.jpg

I tried using RegEx with this command to preview the new names:

Get-ChildItem | % { $_.Name -replace "(.*[^0-9])([0-9]{1}\.jpg)",'$10$2' }

The idea is to get the first part of the name without any digit in first region, and one digit plus the extension in the second region. This will exclude files with two digits. And then I can replace by: first region + 0 + second region.

My problem is the "0" is seen as $10 instead of $1+"0", I don't know how to say it.

What would be the correct syntax? I tried "$10$2", "$1\0$2", "$1`0$2", '$1"0"$2'

Upvotes: 1

Views: 485

Answers (3)

Brian Stephens
Brian Stephens

Reputation: 5261

The correct syntax for indicating a numbered backreference without ambiguity is ${1}.

Here's a corrected version of your statement:

Get-ChildItem | % { $_.Name -replace "(.*\D)(\d\.jpg)",'${1}0$2' }

Note: I also used \D, which is the built-in character class for [^0-9], and \d in place of [0-9].

Upvotes: 0

ojk
ojk

Reputation: 2542

You can use named groups:

$filename -replace "(?<first>.*[^0-9])(?<second>[0-9]{1}\.jpg)", '${first}0${second}'

Upvotes: 1

vks
vks

Reputation: 67968

'"$1"0$2'

This should do it .

Upvotes: 0

Related Questions