Frage

I want to rename 2 files "Data1.txt" to "Log1.rtf" and "Data2.txt" to "Log2.rtf"

I am currently using this code

@ECHO OFF
FOR %%I IN ("%~dp0*.txt") DO (
SET "ext=%%~xI"
SETLOCAL EnableDelayedExpansion
RENAME "%%I" "%%~nI!Log.rtf"
ENDLOCAL
)

But it give output "data1log.rtf" and "data2log.rtf"

War es hilfreich?

Lösung

of course:

RENAME "%%I" "%%~nI!Log.rtf"

But it give output data1log.rtf and data2log.rtf

btw. what do you try to achive with setlocal delayedexpansion and that single ! ?

EDIT: if you insist in doing it with for (because perhaps, you have many files to rename):

@echo off
setlocal enabledelayedexpansion
for %%i in (*.txt) do (
 set file=%%i
 set file=!file:Data=Log!
 set file=!file:.txt=.rtf!
 echo ren %%i !file!
)

the first set sets the variable file to the filename

the second one replaces Data with Log

the third one replaces .txt with .rtf

then rename original filename (%%i) to the changed filename (!file!)

(the echo is there to just show the command on screen instead of really renaming files. Good for testing. If you are sure, that the code does, what you want, just remove the echo)

the setlocal enabledelayedexpansion is needed to use a variable, that is changed inside a block (between ( and )) inside the same block. Therefore you have to use the variable as !var! instead of %var%

Note: of course this code could be improved, but as a beginner: keep it as simple (and readable) as possible. For example, this code will replace Data, but not data or DATA, it will not handle spaces in filenames, ...

Andere Tipps

It might work better if you used separate code to rename each of the files, or does that defeat the object? this website shows how to rename a file using command line: http://www.sevenforums.com/tutorials/56013-file-folder-rename-command-prompt.html

for %%a in ("%~dp0data*.txt"
) do for /f "delims=DdAaTt" %%b in ("%%~na"
) do echo ren "%%~fa" "log%%b.rtf"

It just iterates over the indicated list of files, and for each filename, uses the unnecesary characters as delimiters for an aditional for loop. That way only the number is left and used to rename the file.

Commands to rename are echoed to console. If output is correct, remove the echo command to rename the files.

User mv command to rename files in windows (Using CLI)

As mentioned in above answer, mv command can be used in windows as well to rename the filename. I tried rename and ren commands s suggested, but I was getting error: bash: ren: command not found.

Use below to change the filename: mv filename new_filename

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top