for loop - Creating a batch file to rename TXT files based on content (removing inappropriate syntax) -


i trying create batch file allow me rename files in folder based on text located within test file itself. have pasted first 4 lines text below:

09-nov-16  07:50                              hand-held driver report                                              page:  1                                               xyz company - ar1          date > 11/09/16    driver > 1010    driver name > mike smith truck > 4719 

i trying name each folder date-driver name-truck. need drop "/"'s in date field. incredibly appreciated!

@echo off setlocal set "sourcedir=u:\sourcedir" /f "delims=" %%x in (  'dir /b /a-d "%sourcedir%\*.txt" '  ) (  set "oldname=%%x"  set "newname="  set "drivname="  rem detect line 4 ">"  rem process first found in file  /f "usebackqtokens=1-5delims=>" %%a in (   "%%x") if not defined newname if "%%e" neq "" (   rem process date %%i, %%j, %%k   /f "tokens=1-3delims=/ " %%i in ("%%b") (    rem build drivname    call :procname %%d    rem build new filename , rename file    call :build %%k %%i %%j %%e   )   if not defined newname echo %%x not renamed  ) )  goto :eof  :procname if "%2"=="" goto :eof set "drivname=%drivname% %1" shift goto procname  :build if not defined drivname goto :eof set "newname=%1%2%3-%drivname:~1%-%4" if /i "%oldname%" neq "%newname%" (  echo(ren "%sourcedir%\%oldname%" "%newname%" ) goto :eof 

you need change setting of sourcedir suit circumstances.

the required ren commands merely echoed testing purposes. after you've verified commands correct, change echo(ren ren rename files.

relatively simple:

process each filename %%x. filename, line containing 4 > when line found (%%e non-empty) date in %%b, parse %%i,j,k , process name+truck string in %%d. finally, build elements - year in %%k, month in %%i, day in %%j, trucknumber in %%e , drivername in %drivname%.

the :build routine ensures drivname exists , builds new filename supplied parameters , drivname. if new , old names same (case-insensitive) rename produce error (file has been processed previously) skip rename. since newname established in :build routine, once rename has happened, won't repeated.

finally, if there no newname set up, file hasn't got line of required format, report fact.


Comments