【问题标题】:Creating a batch file to modify the filenames in a directory创建批处理文件以修改目录中的文件名
【发布时间】:2016-12-12 11:01:34
【问题描述】:

我正在尝试构建一个批处理文件。

我在一个文件夹中有 30 个 csv 文件

我的目的是

  1. 获取每个文件名(例如097_021216_192332.csv)
  2. 提取前 3 位数字
  3. 将其与我标记了另一个字符串的查找表 (lookup1.bat) 进行比较

EG:lookup1.bat

@echo 107=B_05-
@echo 097=B_06-
@echo 149=B_07-
@echo 109=B_08-
@echo 101=B_09-
@echo 105=B_10-
@echo 098=B_11-    

所以在这里我会得到“B_06-”

  1. 使用此“B_06-”前缀修改文件名并重命名文件

这是我的代码,我只有关于循环的基本想法,而且我很挣扎。感谢您的帮助。

@echo on

setlocal enabledelayedexpansion


for %%a in ("*.csv") do ( 
    set FileName=%%~na
    goto:stepa
    goto:eof

)
:stepa
for /f "tokens=1 delims=_" %%a in ("%FileName%") do ( 
    set A=%%a 
    echo %A%
    )

@SET MN=%A%
@FOR /F "tokens=1,2 delims==" %%i IN ('lookup1.bat') DO @IF %%i EQU %MN% SET MW=%%j

@ECHO The board number corresponding to %MN% is %MW%.

set "str=%MW%%FileName%"
echo "%str%"    

Ren "!FileName!" "!str!"

:eof

【问题讨论】:

    标签: csv batch-file for-loop nested


    【解决方案1】:

    您的程序结构存在一系列问题。如果你想从for 命令中调用子程序,正确的方法是使用call,而不是goto,并且goto :eof 命令必须放在之后 em> for 结束。不过,这段代码很简单,不需要子程序。

    如果您使用 array 只加载一次表格,然后通过 index em>。

    @echo off
    setlocal EnableDelayedExpansion
    
    rem Create the lookup file with lookup1.bat file,
    rem this program create lines like this one:
    rem 097=B_06-
    call lookup1.bat > lookup1.txt
    
    rem Load the lookup table from the file,
    rem this method create _array elements_ like this one:
    rem set "table[097]=B_06-"
    for /F "tokens=1,2 delims==" %%a in (lookup1.txt) do set "table[%%a]=%%b"
    
    rem Process the files in current folder,
    rem file name format is this:
    rem ###_restOfFileName.csv
    for /F "tokens=1* delims=_" %%a in ('dir /A:-D /B *.csv') do (
       @ECHO The board number corresponding to %%a is !table[%%a]!.
       ren "%%a_%%b" "!table[%%a]!%%b"
    )
    

    您可以通过放置在for 中的附加if not defined table[%%a] ... 命令来测试是否没有为文件定义板号。

    您可以使用文本编辑器直接创建lookup1.txt 文件;只需从lookup1.bat 中删除所有这些@echo 部分并更改扩展名。

    您可以在this answer 上查看有关批处理文件中数组使用的详细说明。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-25
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多