Reputation: 59
Have tried to rename files in a folder with this script, but its seems not to work
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=*.txt
SET new="c:\path to file that contains the listed names"
for /f "tokens=*" %%f in ('dir /b *.txt') do (
SET newname=%%f
SET newname=!newname:%old%=%new%!
move "%%f" "!newname!"
)
what am trying to achieve is my script should pick set of listed names in a file and rename each file in the specified folder accordingly
Upvotes: 0
Views: 588
Reputation: 67206
First you said you want to rename each file "accordingly" (accordingly to what?), and later in a comment you said you try to rename files "with a set of listed names in a file". This point cause several additional questions: Have this file one name in each line? Must the first file listed by dir /b *.txt
match the first name listed in the file, and so on? Any other option? (Why do you use a move
command to do a "rename"?).
Because the objective is not clear, we can not said if your code is right or not. However, this is what your code does. Suppose the first file is "firstFile.txt"; then this section:
SET newname=%%f
SET newname=!newname:%old%=%new%!
move "%%f" "!newname!"
is executed this way:
SET newname=firstFile.txt
SET newname=!newname:*.txt="c:\path to file that contains the listed names"!
Previous line replace from the beginning of newname until ".txt" (that is, the entire value) by "c:\path to file that contains the listed names"
, so the next line is executed this way:
move "firstFile.txt" ""c:\path to file that contains the listed names""
that correctly should move the file into the given path even if it contains a pair of quotes at each side.
If the objective would be "Rename files in a folder to the names listed in a text file one-by-one", then you must do a merge between two lists: the file list created by dir /b *.txt
and the name list stored in the file.
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=*.txt
SET new="c:\path to file that contains the listed names"
< %new% (for /f "tokens=*" %%f in ('dir /b %old%') do (
ren Read the next name from the redirected input file
SET /P newname=
ren "%%f" "!newname!"
))
If this is not what you want, please clearly describe the desired process...
Upvotes: 1
Reputation: 837
test this script
@echo off
set prefix=new
setlocal EnableDelayedExpansion
for /f "delims=" %%a in ('dir *.txt /b') do (
set name=%%~Na
set newName=%prefix%!name:~0,1!X!name:~1,2!!name:~3!
ren "%%a" "!newName!%%~Xa")
Upvotes: 1