批量 - 在线上找到前10个字符的字符串并打印整行

时间:2014-05-22 23:07:38

标签: string batch-file cmd findstr

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

for /f "delims=" %%I in ('dir/B *.txt') do (
    for /f "delims=" %%J in (%%I) do (
        set "=%%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 RANDOMTEXTANDNUMBERS 13121313212153
BBR0621   BBB RANDOMTEXTANDNUMBERS 78975487798797
CCY4488   CCC RANDOMTEXTANDNUMBERS 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

2 个答案:

答案 0 :(得分:2)

@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的输出文件。

答案 1 :(得分: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个字符中并且它们是五个字符长(所有这些都是硬编码的,但可以调整),搜索字符串可以从第一个,第二个开始......从第一个位置开始到第六个位置start(正则表达式中的一个点表示任何字符都可以在该位置)

构建搜索文件后,for循环将遍历.txt个文件,我们每个文件都会搜索findstr,搜索行首({1}} {1}})从生成的文件(/b)中读取正则表达式(/r