Reputation: 1642
I have the following batch script to read an xml file and find a word (in this case, "factory"):
@echo off & setlocal enabledelayedexpansion
for /f "delims=" %%a in ('findstr /C:"factory" xcsconfig.xml') do set content=%%a
set content=%content:*"=%
set content=%content:~0,-1%
echo %content%
exit /b
Here's part of the xml file:
<loggers>
<recorder1>
<add name="factory" value="xlog"/>
<add name="alias" value="WSEnterprise.log"/>
</recorder1>
<recorder2>
<add name="factory" value="weblog"/>
</recorder2>
</loggers>
The code works fine and will always return the "first" founding - value="weblog"/. My question is, is there a way to return the founding under a specific tab? (i.e. I want to search specific under recorder1 instead of record2 tab, and return answer value="xlog"/). Thanks in advance.
EDIT: I changed my expected answer, it was incorrect
Upvotes: 0
Views: 580
Reputation: 566
You can incorporate also the next statements inside the do
block of the for
cycle. I mean:
setlocal EnableDelayedExpansion
for /f "delims=" %%a in ('findstr /C:"factory" xcsconfig.xml') do (
set content=%%a
set content=!content:*"=!
set content=!content:~0,-1!
echo !content!
)
In this way the output is not only the last XML code line but all the code lines that contain the "factory" string in the file considered. Of course this example doesn't echo only a single desired string but this is possible setting a condition to the output of the loop.
Upvotes: 1
Reputation: 41234
Here is a robust tool that can help you - the command looks like this to get the line you need and it can be wrapped in a for /f
loop.
type file.xml |findrepl "<recorder1>" /e:"</recorder1>" /b:"factory"
This uses a helper batch file called findrepl.bat
(by aacini) - download from: https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat
Place findrepl.bat
in the same folder as the batch file or on the path.
Upvotes: 0
Reputation: 79983
@ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sectionstart=recorder1"
SET "insection="
for /f "delims=" %%a in ('type q25062317.txt') do (
IF DEFINED insection (
ECHO "%%a"|FINDSTR /c:"factory" >NUL
IF NOT errorlevel 1 SET "content=%%a"
)
ECHO "%%a"|FINDSTR /i /L /c:"<%sectionstart%>" > NUL
IF NOT ERRORLEVEL 1 SET insection=Y
ECHO "%%a"|FINDSTR /i /L /c:"</%sectionstart%>" > NUL
IF NOT ERRORLEVEL 1 SET "insection="
)
set content=!content:*"=!
set content=!content:*"=!
set content=!content:~1,-1!
echo %content%
GOTO :EOF
I used a file named q25062317.txt
containing your data for my testing.
Upvotes: 4