搜索 txt 文件并打印字符串的下一个单词

搜索 txt 文件并打印字符串的下一个单词

我有一个批处理脚本,它会将整行搜索字符串打印到文本文件中。

   for %%i in (configure.txt) do (
   FINDSTR /C:"Widget Name=" %%i >> output.txt
   )

我的 Configure.txt 文件如下所示:

   <Widget Name="example_1_new" Type="IFC"/>
   <Property Name="exmaple_2_old"/>
   <Content>
   <Widget Name="example_3_new"/>
   <Widget Name="example_4_old"/>
   <Widget Name="exmaple_1_new"/>
   </Content>

我想打印“Widget Name=”(搜索字符串)后的下一个单词(example1),并找到该单词(Example1)的重复项并在其旁边打印其计数,以便我的输出应该是这样的:

   example_1_new 2

有人能告诉我怎么做吗?请注意 configure.txt 有大约 1000 行数据,如上所示。我只是举了一个例子。

答案1

下一个评论代码片段应该完成这项工作:

@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion

rem delete auxiliary variables
for /F %%G in ('set ___ 2^>NUL') do set "%%G=" 

rem count up number of occurrences 
for /F tokens^=2^ delims^=^" %%G in ('
    FINDSTR /C:"Widget Name=" "configure.txt"
  ') do set /A "___%%G+=1"

rem subtract 1 to get number of duplicates
for /F "tokens=1,2 delims==" %%G in ('set ___ 2^>NUL') do set /A "%%G-=1"

REM output: does dot work if your data contains _ underscore
REM for /F "tokens=1,2 delims=_=" %%G in ('set ___ 2^>NUL') do echo %%G %%H

rem alternative output
for /F "tokens=1,2 delims==" %%G in ('set ___ 2^>NUL') do (
  set "_auxvarname=%%G"
  call set "_auxvarname=%%_auxvarname:~3%%"
  SETLOCAL EnableDelayedExpansion
    echo !_auxvarname! %%H
  ENDLOCAL
)

要创建输出文件,请将最后一行更改如下:

rem alternative output
> output.txt (
    for /F "tokens=1,2 delims==" %%G in ('set ___ 2^>NUL') do (
      set "_auxvarname=%%G"
      call set "_auxvarname=%%_auxvarname:~3%%"
      SETLOCAL EnableDelayedExpansion
        echo !_auxvarname! %%H
      ENDLOCAL
    )
)

输出数据合并自原来的问题和来自更新一:

==> type "configure.txt"
<Widget Name="example1"/>
<Property Name="exmaple2"/>
<Content Name="example3"/>
<Widget Name="example4"/>
<Widget Name="example1"/>
<Widget Name="example_1_new" Type="IFC"/>
<Property Name="exmaple_2_old"/>
<Content>
<Widget Name="example_3_new"/>
<Widget Name="example_4_old"/>
<Widget Name="exmaple_1_new"/>
</Content>

==> D:\bat\SU\1094786.bat
example1 1
example4 0
example_1_new 0
example_3_new 0
example_4_old 0
exmaple_1_new 0

相关内容