Thursday, 3 May 2012

Using For Loop to Rename All Files in a Folder


Using For Loop to Rename All Files in a Folder


This is the batch script for windows to rename all files in a folder on windows. This works well perfectly. This was useful for me. It may help others to do the same. I was worried to change the files name and folder using script, atlast i find my script to fix the issue.



rem: Some testing batch command in Windows XP
setlocal ENABLEDELAYEDEXPANSION
@echo off
rem ***************** Test 1 **********************
rem about variables
set var1= This is a variable VAR1
set var2=’This is a variable VAR2′
set var3=”This is a variable VAR3″
echo %var1%
echo ‘%var2%’
echo “%var3%”
rem ***********************************************
rem Conclusion from test 1 is that assigning text
rem value to variable doesn’t need to be quoted
rem ***********************************************
rem **************** Test 2 **********************
rem about for loop
set count=0
for %%a in (1 2 3) do (
echo !count!
set /A count=!count!+1
echo %%a
)
for %%A in (1 2) do for %%B in (A B) DO ECHO %%A%%B
rem **********************************************
rem Conclusion from test 2 is that variable in
rem the for loop has to be single character like
rem %%a. %%var will not work
rem you don’t have to have
rem setlocal ENABLEDELAYEDEXPANSION for the count
rem to work but you do have to use !count! instead
rem of %count%
rem **********************************************
rem **************** Test 3 **********************
rem use for loop to list all .txt file names
for /f %%a in (’dir /b transaction*.txt’) do (
echo %%a
)
rem **********************************************
rem I don’t know what the switch /f in the for
rem statement and the /A switch in the set
rem statement mean but it works.
rem Can someone explain the switch? =)
rem **********************************************
rem **************** Test 4 **********************
rem rename all .txt file so that all of them
rem starts with “trans” instead of “transaction”
for /f “tokens=1,2 delims=_” %%a in (’dir /b transaction*.txt’) do (
if “%%a”==”transaction” echo yes
echo %%a
echo %%b
ren %%a_%%b tran_%%b
)
rem **********************************************
rem The above script works fine. It renames all
rem files named in partern transaction_XXXX.txt
rem to trans_XXXXX.txt
rem “tokens=1,2 delims=_” tells it to separate
rem whatever returned in dir command in two parts
rem using the first “_” found and put the first
rem token in %%a, the second in %%b.
rem It is very powerful and interesting!
rem **********************************************
goto :eof


One additional remark: if you decide NOT to set ENABLEDELAYEDEXPANSION, then the !variable! syntax fails. Not sure if that means that %variable% would work in that situation instead, but just thought I’d be explicit about where ENABLEDELAYEDEXPANSION had an effect (though obviously it’s relevant in other parts too)



No comments: