问题
I would like to rename files that are uploaded to another server from extension .txt to .txt_mvd and move to a different directory for archiving in a Windows batch mode. Can anyone help with what the windows batch script should be?
Thanks.
回答1:
Here is the code
FOR /R C:\your_folder %%d IN (*.txt) DO (
ren %%d %%~nd.txt_mvd
)
%%d is the full file name + path
%%~nd return only the file name without the extension
Using the /R parameter, it will scan folder and subfolder
UPDATE 1
The following code should work as required.
I've added an IF that ignore the subfolders.
FOR /R E:\your_folder\ %%d IN (*.*) DO (
IF %%~dpd==E:\your_folder\ (
ren %%d %%~nd.txt_mvd
)
)
UPDATE 2
Fixed code
FOR /R E:\your_folder\ %%d IN (*.txt) DO (
IF %%~dpd==E:\your_folder\ (
ren %%d %%~nd.txt_mvd
)
)
UPDATE 3
Here is a more generalized and parametrized version of the script.
Change the starting parameter to your need (the first 4 lines of code).
This script first rename the files you choose (1st parameter) in your starting folder (3rd parameter), change the extension to the new one (2nd parameter), and then move the renamed files in the folder of your choice (4th parameter).
set Extension_of_file_you_want_to_renamne_and_move=txt
set New_extension_of_moved_files=txt_mvd
set Folder_that_contain_your_files=C:\Your_starting_folder\
set Folder_where_to_move_your_files=C:\Your_destnation_folder\
FOR /R %Folder_that_contain_your_files% %%d IN (*.%Extension_of_file_you_want_to_renamne_and_move%) DO (
IF %%~dpd==%Folder_that_contain_your_files% (
IF %%~xd==.%Extension_of_file_you_want_to_renamne_and_move% (
ren "%%~d" "%%~nd.%New_extension_of_moved_files%"
move "%%~dpnd.%New_extension_of_moved_files%" "%Folder_where_to_move_your_files%"
)
)
)
when you change the parameter DON'T add any space.
So DON'T change the parameter like that:
set Folder_that_contain_your_files = c:\myFolder <--- WRONG, WON'T WORK, there are unneeded space
instead, write the parameter WITHOUT unneeded space:
set Folder_that_contain_your_files=c:\myFolder <--- OK, THIS WILL WORK, there are no extra spaces
UPDATE 4
Fixed the code, I've added some quotation marks, without them the code wont works if folder name contained spaces.
set Extension_of_file_you_want_to_renamne_and_move=txt
set New_extension_of_moved_files=txt_mvd
set Folder_that_contain_your_files=C:\Your_starting_folder\
set Folder_where_to_move_your_files=C:\Your_destnation_folder\
FOR /R "%Folder_that_contain_your_files%" %%d IN (*.%Extension_of_file_you_want_to_renamne_and_move%) DO (
IF "%%~dpd"=="%Folder_that_contain_your_files%" (
IF %%~xd==.%Extension_of_file_you_want_to_renamne_and_move% (
ren "%%~d" "%%~nd.%New_extension_of_moved_files%"
move "%%~dpnd.%New_extension_of_moved_files%" "%Folder_where_to_move_your_files%"
)
)
)
来源:https://stackoverflow.com/questions/9135367/how-to-rename-and-move-files-to-new-directory