Search txt-files for exact numbers with batchfile, findstr

I'm trying to search for exact numbers stored in text files using a batch file. The files are looking like this:

1, 2, 4, 11, 18, 19, 25, 35, 42, 66, 87, 89.......

The problem is to avoid getting false positives, for instance when I do:

findstr "1" sometxtfile.txt > output

... it also finds the number 11 etc.

I solved this problem with the following:

findstr /R \<1\> sometxtfile.txt > output

But the numbers will have to be stored in variables, and when I do:

findstr /R "\<%variable%,\> sometxtfile.txt > output

... the command-line doesn't respond.

It has to be batch-only solution.


Solution 1:

For extract number with comma + space (or Tab) delimited:

@echo off 

setlocal EnableDelayedExpansion 

for /f useback^tokens^=*delims^= %%i in (`type Q1597471.txt
`)do set "_line=%%~i" && for %%X in (!_line:^, ^= !)do echo=%%~X

endlocal & goto :eof
  • Contents of the file Q1597471.txt...
0, 1, 2, 4, 11, 18, 19, 25, 35, 42, 66, 87, 89
10, 11, 12, 14, 111, 118, 119, 125, 135, 142, 166, 187, 189
210, 211, 212, 214, 2111, 2118, 2119, 2125, 2135, 2142, 2166, 2187, 2189
  • Outputs:
0
1
2
4
11
18
19
25
35
42
66
87
89
10
11
12
14
111
118
119
125
135
142
166
187
189
210
211
212
214
2111
2118
2119
2125
2135
2142
2166
2187
2189


For a different understanding of mine (probably wrong), it would be to get all numbers on the same line concatenated.


@echo off 

cd /d "%~dp0"
setlocal EnableDelayedExpansion

for /f useback^tokens^=*delims^= %%N in (`type Q1597471.txt`)do set/a "_cnt=1" & for /f %%X in ('
%ComSpec% /u /c set/p "'=%%~N"^<nul^|find.exe /v " "^|findstr.exe [0-9]^|find.exe /v /c ""
')do for /f %%n in ('%ComSpec%/u/c set/p "'=%%~N"^<nul^|find.exe /v " "^|findstr.exe [0-9]
')do if %%~X equ 1 (echo\%%~n) else if %%~X equ !_cnt! (echo=!_n: =!%%~n && set "_n="
     ) else (set /a "_cnt+=1" && call set "_n=!_n!%%~n")
    
endlocal & goto :eof

This alphabet soup in synthesis will:

  1. Take line by line and count the occurrences of numbers

  2. The flow per line will give the number of digits I need to extract/compose per line

  3. The number of digits tells me how many times per loop (in the last) I will answer concatenating the output of the variable (digit by digit)

If I don't understand, let me know, my English is terrible squared... The current in/out is some like:

Line in: 1, 2, 4, 11, 18, 19, 25, 35, 42, 66, 87, 89
Line out 124111819253542668789


Obs.: 1. Tested in a file containing a comma + Tab and containing comma + space.

Obs.: 2. Put the bat in the same folder and edit the file name Q1597471.txt for the file name/target.