【问题标题】:Batch - find a string in first 10 characters on line and print whole line批处理 - 在行的前 10 个字符中查找一个字符串并打印整行
【发布时间】:2014-05-22 23:07:37
【问题描述】:

我在使用 findstr 命令时遇到问题。 我正在使用批处理文件执行一个过程,该过程将搜索文件夹中的所有 .txt 并打印出在前 10 个字符中包含先前定义的字符串的行。 到目前为止,我一直在使用这批:

for /f "delims=" %%I in ('dir/B *.txt') 做 (
    for /f "delims=" %%J in (%%I) 做 (
        设置“=%%J”
        call echo %%:~0,10%%|findstr "R0621 32411"&&call echo %%_%% >> search.txt
    )
)
endlocal 
然而,不知何故,这批不会打印出包含 R0621 或 32411 等字符串的行。这是一个错误吗? 当我尝试典型的 findstr 批处理时,它可以正常工作并打印出行。例如这个: findstr "R0621 32411" *.txt >> search.txt 此批处理搜索的 .txt 文件如下所示: AA32411 AAA 随机文本和数字 13121313212153 BBR0621 BBB 随机文本和数字 78975487798797 CCY4488 CCC 随机文本和数字 44455577799998 我不能使用 findstr,因为它会在 10 个字符之后找到字符串以及我不需要的那些行(我只需要那些我在每行的前 10 个字符中定义的字符串)。

还有其他选择吗?我试图搜索互联网,但在任何地方都找不到任何帮助。 另外为了更好地理解你可以查看我之前的帖子Batch to find a string of number&letter combination only in first 10 characters (in a txt file) per row and print the whole row

【问题讨论】:

    标签: string batch-file cmd findstr


    【解决方案1】:
    @echo off
    setlocal EnableDelayedExpansion
    
    rem Seek the target strings in all .txt files
    (for /F "tokens=1* delims=:" %%a in ('findstr "R0621 32411" *.txt') do (
       rem Check that the target string(s) exists in first 10 characters of found lines
       set "line=%%b"
       rem Get just the first 10 characters
       set "tenChars=!line:~0,10!"
       rem If R0621 was in first 10 characters
       if "!tenChars:R0621=!" neq "!tenChars!" (
          echo !line!
       rem If 32411 was in first 10 characters
       ) else if "!tenChars:32411=!" neq "!tenChars!" (
          echo !line!
       )
    )) > search.out
    

    请注意,如果输出文件有 .txt 扩展名,它将包含在原始 findstr 中!您可以在末尾使用ren search.out search.txt 命令以正确的扩展名重命名输出文件,或者在不同的目录中创建扩展名为 .txt 的输出文件。

    【讨论】:

      【解决方案2】:
      @echo off
          setlocal enableextensions
      
          set "tempFile=%temp%\%~nx0.tmp"
          set "outputFile=search.out"
      
          (for %%a in ( 
              R0621 .R0621 ..R0621 ...R0621 ....R0621 .....R0621
              32411 .32411 ..32411 ...32411 ....32411 .....32411
          ) do @echo %%a) > "%tempFile%"
      
          type nul > "%outputFile%"
          for %%a in (*.txt) do findstr /r /b /g:"%tempFile%" "%%~a" >> "%outputFile%"
      
          del /q "%tempFile%" >nul 2>nul
      
          endlocal
      

      它只是用适当的正则表达式构造一个临时文件来搜索。由于字符串应该位于前 10 个字符中并且它们是 5 个字符长(所有这些都是硬编码的,但可以调整),搜索字符串可以从第一个、第二个、...开始到行的第六个位置开始(正则表达式中的点表示任何字符都可以在该位置)

      一旦构建了搜索文件,for 循环将遍历 .txt 文件,我们使用 findstr 搜索每个文件,在行首 (/b) 搜索常规从生成的文件 (/g:) 中读取的表达式 (/r)

      【讨论】:

      • 您好,尝试过并且也可以使用,但无法将 2 个回复标记为答案,因此我在 Aacini 第一次发布时标记了他。无论如何,这也很好用!谢谢! :)
      猜你喜欢
      • 2013-09-20
      • 2014-10-17
      • 2022-08-06
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      相关资源
      最近更新 更多