@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "outfile=%destdir%\outfile.txt"
(
FOR /f "delims=" %%a IN (
'dir /b /a-d "%sourcedir%\*.txt" '
) DO (
SET "filename=%%a"
FOR /f "tokens=1*delims=[]" %%h IN ('find /v /n "" "%sourcedir%\%%a"') DO (
IF "%%h"=="56" SET "first=%%i"
IF "%%h"=="66" SET "second=%%i"&CALL :rentxt
)
)
)>"%outfile%"
GOTO :EOF
:rentxt
FOR %%p IN (%first%) DO SET "part1=%%~p"
FOR %%p IN (%second%) DO SET "part2=%%~p"
ECHO REN "%sourcedir%\%filename%" "%part1% %part2%.txt"
GOTO :eof
You would need to change the settings of sourcedir
and destdir
to suit your circumstances.
Produces the file defined as %outfile%
Meh - I'm bored, so a few minutes of light relief...
I set the names of directories an files into variables for convenience - to test the procedure on my u:
drive.
As written, the code should produce a list of the rename commands it intends to perform in the file nominated as outfile
. This allows you to examine the file to determine whether there are any errors in the data in the files (such that lines 56/66 do not follow the form described) without taking action.
To actually rename the files when the testing-for-veracity is complete, simply remove the ECHO
keyword in the ECHO REN...
line. This will perform the actual rename instead of simply reporting it. The report is then irrelevant, so the single (
line before the for...%%a...
can be removed along with the )>"%outfile%"
line.
First, the for...%%a
performs a directory list of the *.txt
files in the source directory, and assigns the filenames found in turn to %%a
. The /b
and /a-d
switches produce a basic (name-only) format and suppress the directory names found respectively.
The find
searches for lines in the file which /v
do not match ""
(which will be every line - even empty ones) and /n
number the lines within square brackets. The for/f
reads each line of the find
output, using [
and ]
as delimiters, so the line number appears as the first "token" into %%h
and the line contents as the second token (%%i
).
Then select line 56 and 66 into separate variables, and note that filename
contains potatoes.
When line 66 is found, we call the subroutine :rentxt
which processes the strings in first
and second
from lines 56 and 66 respectively. Since each line consists of a series of comma-separated strings, and comma is a separator, the variables part*
are assigned each of these strings in turn, so the for
loop ends with the last variable assigned to part*
. The ~
conveniently removes any enclosing quotes.
Then, since we have the parts of the lines and the original filename now safely in variables, all we need to do is build the rename instruction and well - echo
it for verification, or with the echo
removed, rename the file.