Can I search for multiple strings in one "find" command in batch script?
Asked Answered
A

3

11

I have a windows batch script that will look for a string within a file

find /i "WD6"  %Inputpath%file.txt
if %errorlevel% == 0 GOTO somestuff

Currently this is what my code looks like. I've come across a new string I want to search for in the same file and do the same action if it finds it, it stored it in a variable called %acctg_cyc% can I search for both strings in one line of code? I tried this:

find /i "WD6" %acctg_cyc%  %Inputpath%file.txt
if %errorlevel% == 0 GOTO somestuff

But it seems to ignore the %acctg_cyc% and only look for "WD6" in file.txt. I tried testing where %acctg_cyc% is in file.txt and when it is not and it passes both times.

Any thoughts? I know I could do this in more lines of code but I'm really trying to avoid that right now. Maybe it's just not possible.

Thank you for any help!

Accessary answered 20/7, 2015 at 14:10 Comment(0)
J
16

find isn't very powerful. It searches for one string only (even if it is two words): find "my string" file.txt looks for the string my string.

findstr has much more power, but you have to be careful how to use it:

findstr "hello world" file.txt 

finds any line, that contains either hello or world or both of them.

see findstr /? for more info.

Finding both words in one line is possible with (find or findstr):

find "word1" file.txt|find "word2"

finding both words scattered over the file (find or findstr):

find "word1" file.txt && find "word2" file.txt
if %errorlevel%==0 echo file contains both words
Jevons answered 20/7, 2015 at 14:14 Comment(2)
The find "word1" file.txt|find "word2"does not appear to be working.Wore
Also you can use findstr /c:"test1 test2" flag for whole strings.Wore
P
9

I tried findstr with multiple /C: arguments (one for each to be searched sentence) which did the trick in my case. So this is my solution for finding multiple sentences in one file and redirect the output:

findstr /C:"the first search" /C:" a second search " /C:"and another" sourcefile.txt > results.txt
Pycnidium answered 4/12, 2017 at 8:3 Comment(2)
Thanks, just what I needed. I found it also works piping the output from another program (no file needed) using some_program.exe | findstr /C:"first" /C:"second"Ridge
You can also do it like this: some_program.exe | findstr "first second". If you want to find the string "first second" the syntax is some_program.exe | findstr /C:"first second"Ellissa
O
0

I used this. Maybe not much orthodox, but works! It waits until browsers dismiss

:do_while_loop
rem ECHO LOOP %result%
rem pause
tasklist /NH | find "iexplore.exe"
set result=%ERRORLEVEL%
tasklist /NH | find "firefox.exe"
set result=%result%%ERRORLEVEL%
if not "%result%"=="11" goto :do_while_loop
Oof answered 5/3, 2018 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.