解析和重命名文本文件

时间:2016-03-22 16:43:51

标签: windows batch-file scripting

我需要将所有这些文件重命名为第3行的6个字符的部件号(306391)。

目前我有:

setlocal enabledelayedexpansion 

set first=1

for /f "skip=3 delims= " %%a in (Name.txt) do ( 

   if !first! ==1 (

   set first=0

echo %%a > out.txt
ren Name.txt %%a.txt

 )
)

找到6位数的部件号,并将文件重命名为正确的名称。但是,如果我使用* .txt而不是.txt文件的实际名称,则会中断。我需要它来处理目录中的所有.txt文件。

2 个答案:

答案 0 :(得分:2)

使用另一个for /f循环围绕for循环,然后在ren命令中引用外循环变量。您还可以通过使用if defined进行布尔检查来消除延迟扩展的需要。我在这里和那里进行了其他调整。只要问你是否想要细节。

@echo off
setlocal

for %%I in (*.txt) do (

    set first=

    for /f "usebackq skip=3" %%a in ("%%~fI") do ( 

        if not defined first (

            set first=1

            echo %%~nxI ^> %%a.txt
            rem // uncomment this when you're satisfied that it works correctly
            rem // ren "%%~fI" "%%a.txt"

        )
    )
)

答案 1 :(得分:1)

此方法应该运行得更快,特别是如果文件很大,因为每个文件只读取4行(而不是整个文件):

@echo off
setlocal EnableDelayedExpansion

rem Process all .txt files
for %%f in (*.txt) do (

   rem Read the 4th line
   (for /L %%i in (1,1,4) do set /P "line4=") < "%%f"

   rem Rename the file
   for /F %%a in ("!line4!") do ECHO ren "%%f" "%%a.txt"

)