Reputation: 131
I would like to create a Windows batch file "printFileNames.bat" that print custom file names as follows:
Adobe_1
, DIFX_2
, WinRAR_3
...
I cannot figure out how to work with variables in a loop. This is what I have:
for /r C:\myDir\ %%i in (*) do (
set counter=counter+1
set myFileName=%%i+counter
echo myFileName >> C:\list.txt
)
Upvotes: 2
Views: 1429
Reputation: 32930
Three things to know:
set /a
command (the documentation is a bit outdated though).if
statements inside the for
loop, they will break the loop. You can use call
to call an inner subroutine, and users if
from there. The parameters in the subroutine are passed through the variables %1
, %2
, etc... (just like in an ordinary batch file).%%f
. If you want to extract just the name without the extension, use the %%~nf
form.That being said, try the following code:
@echo off
set counter=0
for /r "C:\myDir\" %%f in (*) do (
set /a counter+=1
call :HandleFile "%%f"
)
goto :eof
:HandleFile
if "%~x1"==".jpg" goto :eof
if "%~x1"==".gif" goto :eof
set "myFileName=%~n1_%counter%"
for %%^" in ("") do >>C:\list.txt echo %%~"%myFileName%
EDIT: fixed the script to handle special file names and skip files with certain extensions.
Hope it helps!
Upvotes: 3
Reputation: 77677
It is possible to obtain the required output without using an explicit counter:
@ECHO OFF
FOR /F "delims=: tokens=1*" %%R IN ('DIR /A-D-H /B /S D:\to_delete\* ^| FINDSTR /N .') DO (
ECHO %%~dpnS_%%R%%~xS
)
The DIR
command provides the list of files, FINDSTR
supplies it with numbers, the FOR /F
loop processes thee output of FINDSTR
to separate numbers from file names and ECHO
produces the final output where numbers are appended to the file names.
Note that the numbers get appended to the names, i.e. before the extensions, so that a file name like this:
D:\path\name.ext
changes to something like this:
D:\path\name_1.ext
If you actually want it to be like this:
D:\path\name.ext_1
replace the ECHO
command above with the following:
ECHO %%S_%%R
Upvotes: 4
Reputation: 1678
@echo off
setLocal EnableDelayedExpansion
set N=0
for /f "tokens=1 delims=." %%i in ('dir /b C:\mydir\') do (
set /a N+=1
echo %%i_!N!
)
Upvotes: 1
Reputation: 82307
You need delayed expansion to access the value of the counter in your loop.
And for incrementing your counter you need the SET /A
switch.
setlocal EnableDelayedExpansion
set counter=0
for /r C:\myDir\ %%i in (*) do (
set /a counter=counter+1
set "myFileName=%%i_!counter!"
echo !myFileName!>> C:\list.txt
)
This would fail if your filenames contains exclamation marks !
, then you need a more stable version like this one
setlocal DisableDelayedExpansion
set counter=0
for /r C:\myDir\ %%i in (*) do (
set /a counter=counter+1
set "filename=%%i"
setlocal EnableDelayedExpansion
set "myFileName=!filename!_!counter!"
echo !myFileName!>> C:\list.txt
endlocal
)
Upvotes: 1