Delete all zeroes at the beginning of files names

Viewed 64

I have some documents in a file starting with different numbers of zeroes. I would like to delete all of these zeroes at the beginning of files.

For example

From

010 document.docx
0002  document.docx
030  document.docx

to

10 document.docx
2  document.docx
30  document.docx

I know I can delete these zeroes one by one using the following command.

Get-ChildItem *.docx | Rename-Item -NewName { [string]($_.Name).Substring(1) }

But can I do this by one command?

2 Answers

Use a regular expression to remove leading zeroes from the file names.

Get-ChildItem *.docx | Rename-Item -NewName { $_.Name -replace '^0+' }

^ matches the beginning of a string (in this case the file name). 0+ matches one or more consecutive zeroes.

An alternative would be to

  • replace multiple spaces with one and
  • pad left with zeroes to a unique length

Get-ChildItem [0-9]*.docx|
  Rename-Item -NewName {[regex]::Replace(($_.Name -replace ' +',' '),
                        '^\d+',{$args[0].Value.PadLeft(4,'0')})}

>gci *.docx

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       2019-01-04     21:40              2 0002 document.docx
-a----       2019-01-04     21:40              2 0010 document.docx
-a----       2019-01-04     21:40              2 0030 document.docx
Related