【问题标题】:Batch scripting - parsing file line by line and finding string批处理脚本 - 逐行解析文件并查找字符串
【发布时间】:2021-02-24 10:23:17
【问题描述】:

我正在尝试使用批处理脚本逐行解析 .txt 文件,直到找到“arg =”字符串,然后得到以下数字。为了把它放到上下文中,我正在尝试解析这个 gdb.txt 文件

warning: No executable has been specified and target does not support
determining executable automatically.  Try using the "file" command.
0x00007c2c in ?? ()
Loading section .sec1, size 0x20000 lma 0x0
Start address 0x8560, load size 131072
Transfer rate: 103 KB/sec, 1110 bytes/write.
Command Executed successfully: semihosting enable

Breakpoint 1 at 0x790a: file C:\LMA\ws_new\wam_sdk1886.31.001.1C_ver1\src\sdk\wam\bsp\detail/exit.c, line 21.
Note: automatically using hardware breakpoints for read-only addresses.

Breakpoint 1, exit (arg=0) at C:\LMA\ws_new\wam_sdk1886.31.001.1C_ver1\src\sdk\wam\bsp\detail/exit.c:21
21    volatile std::uint8_t a = 0;
arg = 0
[Inferior 1 (Remote target) detached]

我想出了这几行批处理脚本:

@echo off

for /f delims^=^ eol^= %%A in (gdb.txt) Do (
  echo %%A
  findstr /c:"arg =" %%A>nul 2>nul
  echo %errorlevel%
  )

我希望脚本能够识别带有“arg =”的行,以便之后我可以读取 0。 但是,此脚本似乎无法识别“arg =”并始终将 %errorlevel% 打印为 1。 我在这里错过了什么?

【问题讨论】:

    标签: batch-file scripting


    【解决方案1】:

    为想要的行过滤文件要容易得多,而不是搜索每一行(并且快得多,尤其是对于大文件):

    for /f "tokens=2 delims== " %%A in ('type gdb.txt^|findstr /bic:"arg = "') Do set "var=%%A"
    echo arg is %var%.
    

    注意:如果匹配的行不止一个,这将为您提供最后一个结果。

    【讨论】:

      【解决方案2】:
      @ECHO OFF
      SETLOCAL
      SET "sourcedir=U:\sourcedir"
      SET "filename1=%sourcedir%\q64803488.txt"
      SET "arg="
      FOR /f "usebackq tokens=1-3" %%a IN ("%filename1%") DO (
       IF /i "%%a"=="arg" IF "%%b"=="=" SET "arg=%%c"
      )
      
      ECHO arg found was "%arg%"
      
      GOTO :EOF
      

      您需要更改sourcedir 的设置以适应您的情况。该列表使用适合我的系统的设置。

      我使用了一个名为 q64803488.txt 的文件,其中包含我的测试数据。

      usebackq 选项是必需的,因为我选择在源文件名周围添加引号。

      arg 设置为空以确保它尚未设置。

      对于文件中的每一行,使用默认分隔符集(包括空格)进行标记化并选择前 3 个标记。如果第一个 (%%a) 是 arg/i 不区分大小写),而 %%b 中的第二个是 =,则将第三个 (%%c) 分配给 arg

      【讨论】:

        【解决方案3】:

        如果我在 中这样做,我会这样做:

        @For /F Tokens^=* %%G In ('%SystemRoot%\System32\findstr.exe /BIRC:"arg = [0123456789]" "gdb.txt" 2^> NUL') Do @Set /A %%G 2> NUL
        @Set arg & Pause
        

        第二行只是为了显示结果。你应该用你自己的代码替换它。

        第一行也可以缩短,(虽然我不推荐)

        @For /F Tokens^=* %%G In ('FindStr /BIRC:"arg = [0-9]" gdb.txt')Do @Set /A %%G
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-04-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-17
          • 2021-06-17
          相关资源
          最近更新 更多