Search code examples
stringbatch-filecmdfindstr

Batch - find a string in first 10 characters on line and print whole line


I am having trouble with findstr command. I am using batch file to execute a proccess that will search all .txt in folder and print out lines that have a string in first 10 characters that is previously defined. So far I have been using this batch:

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    
Somehow this batch however does not print out lines that consists strings like R0621 or 32411. Is this a bug? When I try the typical findstr batch it works and prints out lines just fine. For example this:
findstr "R0621 32411" *.txt >> search.txt
    
.txt files that this batch searches through looks like this:
AA32411   AAA RANDOMTEXTANDNUMBERS 13121313212153
BBR0621   BBB RANDOMTEXTANDNUMBERS 78975487798797
CCY4488   CCC RANDOMTEXTANDNUMBERS 44455577799998
    
I cant use the findstr because it finds string after 10 characters and those lines i dont need (i need only those that have strings i define in first 10 chars per line).

Is there any alternative? I tried to search internet but couldnt find any help anywhere. Also for better understanding you can check my previous thread 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


Solution

  • @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
    

    Please note that if the output file have also .txt extension it would be included in the original findstr! You may use a ren search.out search.txt command at end to rename the output file with the right extension, or create the output file with .txt extension in a different directory.