Renaming file with Batch variable

2019-05-22 21:08发布

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.

3条回答
你好瞎i
2楼-- · 2019-05-22 21:46

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楼-- · 2019-05-22 21:49

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"

查看更多
Emotional °昔
4楼-- · 2019-05-22 21:58

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
查看更多
登录 后发表回答