The following script removes prefix "New book " from each file. Only those files are processed which have "New book " as leading text.
@echo off
set "prefix=New book "
set "prefix_length=9"
for %%i in ("%prefix%*.txt") do (
set "filename=%%i"
setlocal enabledelayedexpansion
ren "!filename!" "!filename:~%prefix_length%!"
endlocal
)
@pause
Script Explained
- The script loops through all text files which have prefix New book with single trailing space. The total count of this prefix is 9.
- Use FOR loop to loop though all such files.
- Store filename in a temporary variable named filename.
- Note that %%i represents replacable parameter of FOR loop.
- At compile time all the commands used inside () are expanded. In other words, strings are expanded by replacing the varibles by their values. For example, "%prefix%*.txt" is replaced as "New book *.txt". Note that * is dynalically replaced by some filename during iteration. Same happens with ren command. It is expanded as ren "!filename!" "!filename:~9!"
- At runtime, the filename variable is replaced by current filename in each iteration of loop. The exclamation sign represents the string expansion at runtime while percent sign represents the string expansion at compile time. Note that expansion of variable happens that is sandwitched between exclamation sign or percent sign. The %% sign is replacable parameter of FOR loop variable. It is not for expansion of set variables.
Tips
- Before running the script, replace ren by echo. It will help you to see the final output on screen without actual result. You can test by the following script:
@echo off
set "prefix=New book "
set "prefix_length=9"
for %%i in ("%prefix%*.txt") do (
set "filename=%%i"
setlocal enabledelayedexpansion
echo "!filename!" "!filename:~%prefix_length%!"
endlocal
)
@pause
No comments:
Post a Comment