开发者

Rename the newest file's extension

I'm trying to write a command script (.cmd file) that will find the newest file and rename its extension.

So if there is:

file1.txt
file2.txt
file3.txt

And file3.txt is the newest, the script should change the extension to .xml, so the end result will be file3.xml.

If I do the following it will rename the file's extension:

move file3.txt file3.xml

But I don't know how to fin开发者_如何学编程d the newest file, and then change its extension.


You could use following batch code:

@echo off
for /F "eol=| delims=" %%F in ('dir /B /O-D /TW "C:\Temp\Test\*.txt" 2^>nul') do (
    ren "C:\Temp\Test\%%F" "%%~nF.xml"
    goto :EOF
)

The command DIR returns a list of file names matching pattern *.txt without path and without any other data because of /B (bare format) sorted reverse according to last modification date (newest first) because of /O-D /TW.

This list is processed line by line by command FOR which executes for first file name the rename command to change the file extension for newest *.txt file in the specified directory. The loop and the batch file processing is exited after renaming first file because of goto :EOF. EOF is a predefined label which means End Of File.

If the current directory on running the batch file is always the directory with the text files, the batch file could be coded also as:

@echo off
for /F "eol=| delims=" %%F in ('dir /B /O-D /TW *.txt 2^>nul') do (
    ren "%%F" "%%~nF.xml"
    goto :EOF
)

delims= turns off splitting the file name returned by command DIR into tokes by spaces in case of the newest file contains 1 or more spaces in file name.

2^>nul redirects any error message because of no *.txt file in current respectively specified directory to device nul to suppress this error message whereby the redirection operator > is escaped here with ^ because of using it within command FOR.

%%~nF means file name only without file extension and dot separating the file extension from file name.

For understanding the used commands even better and how they work here, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • dir /?
  • echo /?
  • for /?
  • goto /?
  • ren /?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜