This batch file with extract the text between (the first) testid=
(if any) on each line and the (first) subsequent ]
(if any),
regardless of where in the line they appear,
with one exception that I was able to identify (see bottom of answer):
@echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%L in (input.txt) do (
set line=%%L
set right1=!line:*testid=!
if not !line! == !right1! (
set left=!right1:~0,1!
if "!left!" == "=" (
set right2=!right1:~1!
for /f "tokens=1 delims=]" %%W in ("!right2!") do (
if not %%W == !right2! (
echo.%%W
)
)
)
)
)
setlocal enabledelayedexpansion
lets you work intelligently
with variables in loops.
for /f "tokens=*" %%L in (input.txt)
reads input.txt
a line at a time
and puts each line into index variable %%L
.
set line=%%L
copies the text into a regular variable,
which is easier to manipulate.
set right1=!line:*testid=!
uses the % var : str1 = str2 %
syntax
for doing a string substitution in a variable expansion
(spaces are added for clarity).
- Using
!
instead of %
because of delayed expansion.
var
is line
, obviously.
str1
is *testid
.
The *
is a wildcard (pattern matching symbol), so this matches
everything up through the first occurrence of testid
in line
.
Note that, while we would like str1
to be *testid=
,
but, unfortunately, it’s impossible for str1
to contain =
,
because =
is the delimiter between str1
and str2
.
str2
is null.
So this replaces everything
up through the first occurrence of testid
in line
with null,
and returns everything after testid
.
- If the line doesn’t contain
testid
,
the above returns the entire line
, unchanged.
So, if line
equals right1
, there was no testid
in the line.
If they are different, proceed to analyze this line.
set left=!right1:~0,1!
extracts the first (leftmost) character
from right1
.
if "!left!" == "="
, the first character after testid
is =
,
so we have found testid=
and we want to continue analyzing the line.
set right2=!right1:~1!
sets right2
to be all of right1
except for the first character; i.e., after the =
.
for /f "tokens=1 delims=]" %%W in ("!right2!")
breaks right2
apart
at the first ]
, putting the text before ]
into %%W
.
- If
%%W == !right2!
, there was no ]
in the line.
- If we found
testid=
and ]
, then %%W
is the text between them.
You should probably assign it to a regular variable.
Disclosure: given the line
[testid=a] and [testid=b]
this batch file will find a
only; it will not find b
.
Given the line
[testid<c] and [testid=d]
the batch file will not find anything; the first testid
throws it off.