G. Walter
G. Walter

Reputation: 13

Batch script to search strings in text file; echo string found or not found

I need a CMD script that is able to search through a text file based on a findstr command that has multiple strings in it to be searched for.


In this case, I have created a text file (kb.txt) that contains the result of the command:

wmic qfe list

The script I need will read the file and searches through it with the findstr command like:

findstr "kb3199321 kb3175631 kb3155567 kb3143345"

If the string is not found, it will output the string that is not found. The same goes for those that have been found. Example of output:

kb3199321 not found
kb3175631 found
kb3155567 found
kb3143345 not found

The script should loop through the findstr command for all its strings (not just the 4 listed above, it could be a few dozen to hundreds), and for each of them, echo if the string is found or not.


Note

If the findstr command is too limited (where it can't search through more than a hundred strings), then the script should read off all the strings from another separate text file (e.g. "searchfile.txt"), then search through the "kb.txt" to see if it is able to find the strings, and echo the same wanted results as above

Upvotes: 0

Views: 10067

Answers (1)

phuclv
phuclv

Reputation: 42032

You can't search all the strings and display the results separately. You must search each string independently then check the return value to know if the string exists or not.

Another problem is that wmic prints its output in UTF-16, but findstr doesn't work with Unicode so you'll have to use find (which is enough for this situation).

You can put the strings to search in the search file, line-by-line, then use a for /F loop to go through the content of that file

@echo off

for /F %%f in (searchfile.txt) do (
    find /i "%%f" kb.txt >NUL
    if errorlevel 1 (
        echo %%f not found
    ) else (
        echo %%f found
    )
)

If you want to use findstr for more features then you'll need to convert wmic output to ANSI. For information on how to do that see

Upvotes: 0

Related Questions