简体   繁体   中英

Parse and Rename text files

I need to rename all of these files to the 6 character Part Number(306391) on the 3rd line.

Currently i have:

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

 )
)

Which finds the 6 digit part number and renames the file to the correct name. But breaks if i use *.txt instead of the actual name of the .txt file. I need it to work for all .txt files in the directory.

Surround your for /f loop with another for loop, then reference the outer loop variable in your ren command. You can also eliminate the need for delayed expansion by using if defined for boolean checks. I put in other tweaks here and there. Just ask if you want details.

@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"

        )
    )
)

This method should run faster, specially if the files are large, because just 4 lines of each file are read (instead of the whole file):

@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"

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM