Renaming file with Batch variable

2019-05-22 21:12发布

问题:

I have the following code:

set DATE=%date% 
echo %DATE% 
set DAY=%DATE:~0,2% 
echo %DAY% 
rename file09.txt file%DAY%09.txt
pause

It is supposed to rename a text file and put the day of the month in the file name. I am however getting a syntax error on the rename command.

I think the problem is in inserting the variable into the file name. Any help would be appreciated. The echos are just in the program for my own reference.

回答1:

As has already been stated - your code as pasted had trailing spaces on many lines and the spaces often matter. I posted this because you had reused the system DATE variable name and that causes issues, and to show you that quotes are often helpful - and needed with long filenames.

set "D=%date%"
echo "%D%"
set "DAY=%D:~0,2%"
echo "%DAY%"
rename "file09.txt" "file%DAY%09.txt"
pause


回答2:

you might have trailing spaces in the set command. Just try this:

set "DAY=%DATE:~0,2%"

btw. with set DATE=%date% you doesn't create a new variable. Variables must have case insensitive unique Names.



回答3:

The problem was the date configuration, because of that the content of the variables is wrong.

Really use quotation marks worked as it ensures full name if the variables have spaces or unusual characters.

Review my post for view the Endoro answer..it works right for me

Renaming file with Batch variable doesnt work with another user profile "Renaming file with Batch variable doesnt work with another user profile"