I have multiple Invoice_Term1........txt
files in a directory, e.g. Invoice
. The content of each of file contains:
Invoice No : B23335 ...
Account Code : ABDU16 ...
How do I loop through each txt file, FINDSTR Invoice No :
, but copy B23335
and FINDSTR Account Code :
, and copy ABDU16
?
Concerns are that each Invoice No
and Account Code
are different in character length and there are other words after the number and code strings, (represented as ...
in my above example content), separated from it with a space character.
The intention is to rename the files, using the above example, to Invoice_Term1.......B23335_ABDU16.txt
.
I tried using AI, but definitely need a lot of changes, or even a full rewrite.
@ECHO OFF
FOR %%F IN (*.txt) DO (
FINDSTR /R /C:"Invoice No :" /C:"Account Code :" \"%%F\" > temp.txt
SET /P KEYWORD1=<temp.txt
SET /P KEYWORD2=<temp.txt
FOR /F "tokens=3 delims= " %%A IN ("%KEYWORD1%") DO (
FOR /F "tokens=3 delims= " %%B IN ("%KEYWORD2%") DO (
REN \"%%F\" %%A%%B.txt
)
)
DEL temp.txt
)
I need some expert assistance.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following setting for the directory is a name
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
PUSHD "%sourcedir%"
FOR /f "delims=" %%e IN ('dir /b /a-d *.txt') DO (
FOR /f "usebackqtokens=1-4" %%g IN ("%%e") DO (
IF /i "%%g%%h%%i"=="InvoiceNo:" SET "Inv=%%j"
IF /i "%%g%%h%%i"=="AccountCode:" SET "Account=%%j"
)
ECHO REN "%%e" "%%~ne!Inv!_!Account!.txt"
)
popd
GOTO :EOF
Noting that Invoice No : B23335
is in the before-file and B233335
is in the desired new name (one extra 3
- presumed typo)
It is important to specify the form of ......
since the presence of, eg. spaces in the filename may affect the code that's required to process it.
Note that renaming a file to samefilenameplusextracharacters.ext is likely to cause for…(mask)…
to reprocess the file. The for /f…('dir…
method builds the filelist first in memory, then processes the filelist.
Switch directories [pushd]
dir /b /a-d
produces a list of filenames-only.
Read each line from file, Butt-up the first 3 tokens as, eg. Invoice
No
:
for testing and grab the fourth token (using the default delimiters) for the variables.
Switch back to original directory [popd]
The required REN commands are merely ECHO
ed for testing purposes. After you've verified that the commands are correct, change ECHO REN
to REN
to actually rename the files.