user1809753
user1809753

Reputation: 165

Batch rename file with variable

I try to rename a file with a variable myVar that I have set in the for loop below. The problem is that rename is not working. Can anybody tell me why?

For /F  %%A in ('"type tmpFile2.txt"') do set myVar=%%A
ren file1.txt file2%myVar%.txt

Upvotes: 3

Views: 5748

Answers (3)

Aacini
Aacini

Reputation: 67216

I could bet that your code is placed inside parentheses like this one:

if some == comparison (
   For /F %%A in ('"type tmpFile2.txt"') do set myVar=%%A
   ren file1.txt file2%myVar%.txt
)

If this is the case, you need to use Delayed Expansion in order to get the value of a variable that was modified inside the block:

setlocal EnableDelayedExpansion
if some == comparison (
   For /F %%A in ('"type tmpFile2.txt"') do set myVar=%%A
   ren file1.txt file2!myVar!.txt
)

For further details, search this or other sites for "delayed expansion".

Upvotes: 3

Hi Please try this code.

 for /F "tokens=*" %%i in (myfile.txt) do (
    set %filename% = %%i
    ren file1.txt file2%filename%.txt
    )

Upvotes: 1

ElektroStudios
ElektroStudios

Reputation: 20464

Your code is working, maybe the problem is with the tmpfile2.txt content (The token),

or maybe the variable value has spaces and thats the reason why is not working,

without the content of the tmpfile2 we can't know why is not working.

Try this way to see what is happenning:

For /F "delims= usebackq" %%# in ("tmpFile2.txt") do (Echo "myVar=%%#" & set "myVar=%%#")
Echo Rename "file1.txt" "file2%myVar%.txt"
Rename "file1.txt" "file2%myVar%.txt"

Or this else:

For /F "delims= usebackq" %%# in ("tmpFile2.txt") do (Rename "file1.txt" "file2%%#.txt")

Upvotes: 0

Related Questions