Having trouble getting the correct command syntax. We need to add a leading zero to a batch of files in a directory on a regular basis. I cannot download and install a software item to do so. The operating system is Windows-7. The length of the filenames varies. i.e. 000165-CityName1.pdf to 0000165-CityName1.pdf 000166-CityNameLonger2.pdf to 0000166-CityNameLonger2.pdf etc. Looking for a rename command that would work, can someone please suggest one, it would be appreciated. I have tried a half dozen without success.
Asked
Active
Viewed 9,762 times
3 Answers
4
This powershell script should work just fine to add a 0 to the beginning of each filename in a folder. Save this script as a .ps1.
Get-ChildItem -Path "C:\temp\cityfiles\" |
Rename-Item -NewName {$_.BaseName.insert(0,'0') + $_.Extension}
This takes every file inside the folder cityfiles and adds a '0' to the beginning of each filename.
Narzard
- 3,840
2
How do I add a leading zero to a batch of filenames?
Use the following command:
for /f %f in ('dir /b *.pdf') do ren "%f" "0%f"
To use in a batch file replace % with %%:
for /f %%f in ('dir /b *.pdf') do ren "%%f" "0%%f"
Example usage:
F:\test\test>dir
Volume in drive F is Expansion
Volume Serial Number is 3656-BB63
Directory of F:\test\test
24/06/2016 21:39 <DIR> .
24/06/2016 21:39 <DIR> ..
24/06/2016 21:38 0 000165-CityName1.pdf
24/06/2016 21:38 0 000166-CityNameLonger2.pdf
2 File(s) 0 bytes
2 Dir(s) 1,769,011,425,280 bytes free
F:\test\test>for /f %f in ('dir /b *.pdf') do ren "%f" "0%f"
F:\test\test>ren "000165-CityName1.pdf" "0000165-CityName1.pdf"
F:\test\test>ren "000166-CityNameLonger2.pdf" "0000166-CityNameLonger2.pdf"
F:\test\test>dir
Volume in drive F is Expansion
Volume Serial Number is 3656-BB63
Directory of F:\test\test
24/06/2016 21:40 <DIR> .
24/06/2016 21:40 <DIR> ..
24/06/2016 21:38 0 0000165-CityName1.pdf
24/06/2016 21:38 0 0000166-CityNameLonger2.pdf
2 File(s) 0 bytes
2 Dir(s) 1,769,011,425,280 bytes free
Further Reading
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- dir - Display a list of files and subfolders.
- for /f - Loop command against the results of another command.
- ren - Rename a file or files.
DavidPostill
- 162,382
0
While you could put this in a bat file and put some options and checking, going to a cmd prompt and cd to the folder you want
- ren .pdf 0.pdf
Will add a zero in front of the name for any pdf
bvaughn
- 751