【问题标题】:How to rename and move files to new directory如何重命名文件并将其移动到新目录
【发布时间】:2012-02-26 11:13:00
【问题描述】:

我想将上传到另一台服务器的文件从扩展名 .txt 重命名为 .txt_mvd 并移动到不同的目录以在 Windows 批处理模式下存档。谁能帮忙看看windows批处理脚本应该是什么?

谢谢。

【问题讨论】:

  • 已尝试使用 Windows powershell。这应该会让你很容易。

标签: file batch-file rename move


【解决方案1】:

这里是代码

FOR  /R C:\your_folder %%d  IN  (*.txt)  DO  (
    ren %%d %%~nd.txt_mvd
)

%%d 是完整的文件名 + 路径
%%~nd 只返回不带扩展名的文件名
使用 /R 参数,它将扫描文件夹和子文件夹

更新 1

以下代码应按要求工作。
我添加了一个忽略子文件夹的 IF。

FOR  /R E:\your_folder\ %%d  IN  (*.*)  DO  (
    IF %%~dpd==E:\your_folder\ (
        ren %%d %%~nd.txt_mvd
    )
)

更新 2

固定代码

FOR  /R E:\your_folder\ %%d  IN  (*.txt)  DO  (
    IF %%~dpd==E:\your_folder\ (
        ren %%d %%~nd.txt_mvd
    )
)

更新 3
这是脚本的更通用和参数化的版本。
根据需要更改起始参数(前 4 行代码)。
此脚本首先重命名您在起始文件夹(第 3 个参数)中选择的文件(第 1 个参数),将扩展名更改为新的(第 2 个参数),然后将重命名的文件移动到您选择的文件夹中(第 4 个参数)。

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%"
        )
    )
)

更改参数时不要添加任何空格。
所以不要这样改变参数:

set Folder_that_contain_your_files = c:\myFolder      <--- WRONG, WON'T WORK, there are unneeded space

改为在没有多余空格的情况下写入参数:

set Folder_that_contain_your_files=c:\myFolder      <--- OK, THIS WILL WORK, there are no extra spaces

更新 4
修正了代码,我添加了一些引号,如果没有它们,如果文件夹名称包含空格,代码将无法工作。

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%"
        )
    )
)

【讨论】:

  • 感谢 Max,提供代码。我能够重命名文件,但它将当前和所有子目录中的所有带有 ext .txt 的文件重命名为 .txt_mvd。我只想更改进入当前目录的新文件并更改扩展名,然后将其移动到存档目录。这可以改变吗?再次感谢。
  • 抱歉,代码运行不正常。它将其他文件的扩展名(包括 .exe)更改为 .txt_mvd。我假设在您的代码中, E:\your_folder\ 是我当前的文件夹?我在哪里提到移动更改的扩展文件的文件夹?您能否解释一下逻辑以及我需要将当前目录放在哪里以及需要将存档目录放在哪里?谢谢!
  • @richard:抱歉,有一个错误。我已经修好了
  • 嗨 Max,在这段代码中,哪个是我的当前目录,哪个应该是移动重命名文件的目录?谢谢。
  • @Richard:我刚刚用更通用的代码版本更新了解决方案,这里有用于起始文件夹、目标文件夹等的显式参数...
猜你喜欢
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多