This batch file with extract the text between (the first)
(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):
for /f "tokens=*" %%L in (input.txt) do (
if not !line! == !right1! (
if "!left!" == "=" (
for /f "tokens=1 delims=]" %%W in ("!right2!") do (
if not %%W == !right2! (
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
set line=%%L copies the text into a regular variable,
which is easier to manipulate.
% var : str1 = str2 % syntax
for doing a string substitution in a variable expansion
(spaces are added for clarity).
! instead of
% because of delayed expansion.
* is a wildcard (pattern matching symbol), so this matches
everything up through the first occurrence of
Note that, while we would like
str1 to be
but, unfortunately, it’s impossible for
str1 to contain
= is the delimiter between
str2 is null.
So this replaces everything
up through the first occurrence of
line with null,
and returns everything after
- If the line doesn’t contain
the above returns the entire
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
if "!left!" == "=", the first character after
so we have found
testid= and we want to continue analyzing the line.
set right2=!right1:~1! sets
right2 to be all of
except for the first character; i.e., after the
for /f "tokens=1 delims=]" %%W in ("!right2!") breaks
at the first
], putting the text before
%%W == !right2!, there was no
] in the line.
- If we found
%%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
Given the line
[testid<c] and [testid=d]
the batch file will not find anything; the first
testid throws it off.