0

I want to rename only .csv files which do not conform to name format guidelines. All other files with incorrect numbers are ok.

correct:

     31_12_99-01.csv
     01_01_00-88.csv

incorrect:

     2_1_00-01.csv

I need help to identify numbers smaller than 10 (only one digit).

Get-ChildItem *.csv -Name |Where{$_.Name -match '\d+'} 

After rename powershell should show all renamed files(new file name) so I can choose to save this list to rename.cfg.

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36
  • Hmm, at least this will list the problem ones. `Get-ChildItem *.csv | Where {$_.Name -match '[^\d]\d[^\d]'}` – js2010 Jun 19 '19 at 18:34
  • I'd like to see what someone else comes up with. This is a nice site to try out regex: https://regex101.com/. I don't know why this doesn't match both single numbers: `'2_1_00-01.csv' -match '(\b|_)\d_'; $matches`. – js2010 Jun 19 '19 at 19:42

1 Answers1

0
get-childitem *.csv |
where name -match '(\b|_)\d_' |
rename-item -newname { $_.name -replace '(\b)(\d_)','${1}0$2' -replace '(_)(\d_)','${1}0$2' } -whatif -passthru

What if: Performing the operation "Rename File" on target "Item: C:\Users\js\foo\2_1_00-01.csv Destination: C:\Users\js\foo\02_01_00-01.csv".

# why doesn't this work?  I guess because the patterns overlap
# rename-item -newname { $_.name -replace '(\b|_)(\d_)','${1}0$2' } -whatif -passthru

EDIT: With negative lookbehind and negative lookahead, sweet. regex: find one-digit number

get-childitem *.csv |
where name -match '(?<!\d)\d(?!\d)' |
rename-item -newname { $_.name -replace '(?<!\d)(\d)(?!\d)','0$1' } -whatif -passthru
js2010
  • 23,033
  • 6
  • 64
  • 66