12. Batch files
If a command line is too long, it will be difficult to read and understand the code. In this case, you should use a batch file. Some examples.
12.1 Add a sequential number to filenames: prefix
Open Notepad++, enter the following code and save the file to 'number1.bat' (in directory 'test')
@echo off
setlocal EnableDelayedExpansion
SET i=0
FOR /f "usebackq tokens=" %%f in (*.txt) DO (
SET /a i+=1
REN "%%f" "!i!%%f.tmp"
)
REN *.tmp *.
To run this file, type at the prompt the filename 'number1.bat' and press Enter.
D:\test>number1.bat [ENTER]
Some explanations:
a. The command @echo off means: 'do not display the commands in this file on the screen'
b. setlocal EnableDelayedExpansion: the value of variables that are modified inside the FOR command are taken by enclosing their
names in exclamation-marks. Otherwise, variable i will always have the value 0 in this case: 'SET i=0')
c. For filenames with spaces, add "usebackq tokens=".
d. A variable in a batch file is represented by %%variable (instead of %variable). So with two percent signs instead of one.
12.2 Add a sequential number to filenames: suffix
Open Notepad++, enter the following code and save the file to 'number2.bat' (in directory 'test')
@echo off
setlocal EnableDelayedExpansion
SET i=0
FOR /f "usebackq tokens=" %%f in (*.txt) DO (
SET /a i+=1
REN "%%f" "%%~nf!i!.tmp"
)
REN *.tmp *.txt
To run this file, type at the prompt the filename 'number2.bat' and press Enter.
D:\test>number2.bat [ENTER]
Explanation:
a. %%~nf expands %%f to a filename only. For more info, enter FOR /? at the prompt.
b. For filenames with spaces, add "usebackq tokens=".
12.3 Add a sequential number as suffix to filenames in sorted order
Open Notepad++, enter the following code and save the file to 'number3.bat' (in directory 'test')
@echo off
setlocal EnableDelayedExpansion
SET i=0
FOR /f "usebackq tokens=" %%f in (DIR "*.txt" /B /O:N) DO (
SET /a i+=1
REN "%%f" "%%~nf!i!.tmp"
)
REN *.tmp *.txt
To run this file, type at the prompt the filename 'number3.bat' and press Enter.
D:\test>number3.bat [ENTER]
Explanation:
the command 'DIR /B' results in a bare list of files that are sorted by '/O:N'
12.4 Command line parameters batch files
Batch files are handy tools. However, they can have security issues, e.g. when using command line arguments. I recommend to read :
www.robvanderwoude.com/battech_inputvalidation_commandline.php
The website www.robvanderwoude.com gives a lot of information, including a tutorial on batch files.