Solved How do I copy and rename files from one dir to another?

January 22, 2020 at 13:54:45
Specs: Windows 10
I am trying to use the FOR loop command in a batch file to copy and rename multiple PDF files from one folder to another. The renamed file uses the first 35 characters of the original PDF file. This is what I have and it doesn't work:

@echo off
setlocal enabledelayedexpansion

for /f %%a IN ('dir /b "C:\Source\*.PDF"') do (
set "fname=%%~na"
copy "%%a" "C:\Destination\!fname:~0,35!.PDF"
)
endlocal

What am I missing?

Thanks!
Irfan


See More: How do I copy and rename files from one dir to another?

Reply ↓  Report •

#1
January 22, 2020 at 18:42:27
✔ Best Answer
If there are spaces in the filenames, you need to add: "tokens=*" to the for loop:
for /f %%a IN ('dir /b "C:\Source\*.PDF"') do (

to:
for /f "tokens=*" %%a IN ('dir /b "C:\Source\*.PDF"') do (

This seemed to fix it in my limited tests


Reply ↓  Report •

#2
January 25, 2020 at 07:39:32
Thanks for the solution, I really appreciate it!

Reply ↓  Report •
Related Solutions


Ask Question