使用批处理脚本将文件重命名为新名称文件夹

时间:2015-04-14 18:37:02

标签: batch-file rename

尝试使用此脚本重命名文件夹中的文件,但似乎无法正常工作

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=*.txt
SET new="c:\path to file that contains the listed names" 
for /f "tokens=*" %%f in ('dir /b *.txt') do (
   SET newname=%%f
   SET newname=!newname:%old%=%new%!
   move "%%f" "!newname!" 
)

我想要实现的是我的脚本应该在文件中选择一组列出的名称并相应地重命名指定文件夹中的每个文件

2 个答案:

答案 0 :(得分:1)

测试此脚本

 @echo off
    set prefix=new

    setlocal EnableDelayedExpansion
    for /f "delims=" %%a in ('dir *.txt /b') do (
                                      set name=%%~Na
                                      set newName=%prefix%!name:~0,1!X!name:~1,2!!name:~3!
                                      ren "%%a" "!newName!%%~Xa")

答案 1 :(得分:1)

首先,您说要重命名每个文件"相应地" (相应的是什么?),稍后在评论中你说你试图用文件"中的一组列出的名称重命名文件"。这一点引起了几个额外的问题:每行中有这个文件一个名字吗? dir /b *.txt列出的第一个文件是否必须与文件中列出的第一个名称匹配,依此类推?还有其他选择吗? (为什么使用move命令执行"重命名"?)。

由于目标不明确,我们不能说您的代码是否正确。但是,这就是您的代码所做的。假设第一个文件是" firstFile.txt&#34 ;;然后这部分:

SET newname=%%f
SET newname=!newname:%old%=%new%!
move "%%f" "!newname!" 

以这种方式执行:

SET newname=firstFile.txt
SET newname=!newname:*.txt="c:\path to file that contains the listed names"!

上一行从newname的开头替换为" .txt" (即{em>整个值)"c:\path to file that contains the listed names",所以下一行以这种方式执行:

move "firstFile.txt" ""c:\path to file that contains the listed names"" 

正确地将文件移动到给定路径中,即使它在每一侧都包含一对引号。

如果目标是"将文件夹中的文件重命名为文本文件中列出的名称逐个",则必须在两个列表之间执行合并dir /b *.txt创建的文件列表和存储在文件中的名称列表。

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=*.txt
SET new="c:\path to file that contains the listed names" 
< %new% (for /f "tokens=*" %%f in ('dir /b %old%') do (
   ren Read the next name from the redirected input file
   SET /P newname=
   ren "%%f" "!newname!" 
))

如果这不是您想要的,请清楚地描述所需的过程...