Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Batch files - Outputting filenames from within a FOR loop

Status
Not open for further replies.

FraserY

Technical User
Apr 25, 2012
2
GB
I am wishing to rename files with a batch command and capture the original and renamed files in a list in order to provide a cross reference (doing a DIR /OS >file both before and after the batch file is not rigorous enough.

The file below carries out the renaming fine, but my understanding is not good enough to get the output bit working (if that is possible even!). Also the output in the example below is different depending on whether output is to file or screen.

Any help would be appreciated to increase my understanding of this.

--------------------------
@echo off
set /a c=%1

setLocal ENABLEDELAYEDEXPANSION

For %%G in (*.tif) do (
echo %%G >infile.txt
ren %%G abc.!c!.tif
set /a c=c+1
echo %%G >outfile.txt
)

endlocal
 
I don't think you can do this in the current format because

1) I don't think you can run a series of commands in a for loop (I could be wrong on this) and

2) if you are looping in a folder and renaming in said folder, it will loop onto itself

What I did was create two batch files and have it copy the files to a different location. Mine were called test1.bat and test2.bat

test1.bat contained
Code:
@echo off
set /A c=1
setLocal ENABLEDELAYEDEXPANSION
For %%G in (*.jpg) do test2.bat %%G
endlocal

test2.bat contained
Code:
echo %1 >> infile.txt
@copy %1 d:\test\abc.%c%.jpg
@if exist "abc.%c%.jpg" @echo abc.%c%.jpg >> outfile.txt
@set /A c=c+1
 
Thanks 'tootiredtocare' for your input. I am trying to avoid the need to copy the files to rename them as they are about 50+Gb of tif images.
In answer to your point re multiple commands in For loop, yes you can do it if you use ( ), as in the fragment.

After sleeping on it I found the answer to the problem - so often the way - see fragment below. I only have to write the name of the file that is about to be renamed as I 'know' what I am about to call it! Obvious in the end.
--------------------------------
set /a c=%1
set param=%2
setLocal ENABLEDELAYEDEXPANSION

FOR %%i in (*.tif) do (
echo %%i >>in.txt
ren %%i %param%!c!.tif
echo %param%!c!.tif >>out.txt
set /a c=c+1
)
endlocal
-------------------------------
All I need to do now is put in a test to stop it renaming again the first file it renamed (can happen depending on the number being used in var 'c' and the original file names).

Aren't Batch commands wonderful!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top