10. More complex replacements

To replace a character regardless of its position, to add a prefix or to add a suffix, we could use the 'FOR' loop.

It's recommended to add the command 'LFNFOR On' to enable Long file name support:
LFNFOR On & FOR %i IN (set) DO command [command parameters]
For brevity, we omit 'LFNFOR On' in the next examples.

10.1 Add a prefix to a filenames with the same characters at the beginning

D:\test>FOR %i IN (file*.txt) DO REN %i prefix_%i [ENTER]
The result is that e.g. file1.txt is renamed to prefix_file1.txt.

The command
D:\test>FOR %i IN (file*.*) DO REN %i prefix_%i [ENTER]
also renames file2.dat to prefix_file2.dat

10.2 Add a prefix to filenames with the same extensions

The command
D:\test>FOR %i IN (*.txt) DO REN %i prefix_%i [ENTER]
makes the 'REN' bug visible. In case of our three original files with filenames 'file1.txt', 'file2.txt' and 'file3.txt', the result will be:

prefix_file2.txt
prefix_file3.txt
prefix_prefix_file1.txt

To avoid the last incorrect filename, we use a little trick:
D:\test>FOR %i IN (*.txt) DO REN %i prefix_%i.tmp & REN *.txt.tmp *. [ENTER]
What does it do? 'file1.txt' will be renamed to 'prefix_file1.txt.tmp', 'file2.txt' to 'prefix_file2.txt.tmp' etc. The command 'REN *.txt.tmp *.' renames all extensions '.txt.tmp' back to '.txt'.

In chapter 11 we'll use the alternative command namely 'FORFILES'.

10.3 Add a suffix to filenames with the same extensions

Here we can avoid a 'FOR' loop:
D:\test>REN *.txt ?????_suffix.txt.tmp & REN *.txt.tmp *. [ENTER]
The number of ? equals the maximum number of characters of the original filename. So, 'file1.txt' will be renamed into 'file1_suffix.txt'.

In case of renaming 'file1.txt', 'file222.txt' and 'file33333.txt', the maximum number of ? characters equals the number of characters of the longest filename: file33333, i.e. 9 characters.
D:\test>REN *.txt ?????????_suffix.txt.tmp & REN *.txt.tmp *. [ENTER]
So, 'file1.txt' will be renamed into 'file1_suffix.txt', 'file222.txt' into 'file222_suffix.txt' and 'file33333.txt' into 'file33333_suffix.txt'.

In chapter 11 we'll use the alternative command namely 'FORFILES'.

10.4 Substitute a character in a specific position

To substitute a character in the 1st and 3rd positions prior to the extension '.txt', type:
D:\test>REN *.txt F?L*.txt [ENTER]
So 'file1.txt' will be renamed in 'FiLe1.txt' and 'temp.txt' into 'FeLmp.txt'.

A 2nd or 3rd character will be added if these characters don't exist: the file '1.txt' will be changed into 'FLL.txt'.