Search code examples
windowsbatch-filefindstr

Find string which include "%" with findstr


Im making a bat-file for windows that will run a simulation. It will then look at the result in the console and search for the string "win%". Ftm I can find anything including win but that gives me alot of unnessesary data.

This is what I got now:

command | findstr win >> file.txt

This gives me alot of unnessesary data.

I want to find:

command | findstr win% >> file.txt

But this dosent work at all....

How can I find the strings including "%"?

Br


Solution

  • Based on your question tags, your command appears within a batch script.

    Percent literals must be escaped as %% within a batch script.

    command | findstr win%% >> file.txt
    

    The above will always work because your search string contains only one percent.

    Note that each side of the pipe is executed in its own cmd.exe process using command line context (not batch). This could lead to a problem, depending on your search string and the current defined variables.

    Suppose you wanted to search for win%lose%. The following might work:

    command | findstr win%%lose%% >>file.txt
    

    It works as long as there is no variable named lose in the environment. Since the FINDSTR command executes in a command line context, the %lose% string is preserved if lose is not defined.

    But if lose is defined, then %lose% is expanded into the value and you get the wrong search. This could be solved by introducing a disappearing caret into the expression. A string like %^lose% will not expand a variable named lose. The variable expansion will include the caret as part of the name, not find anything, and leave the string intact. Afterwards, the normal escape phase will "escape" the l into itself, and the caret disappears. Now this would fail if a variable named ^lose is defined, but that is highly unlikely.

    But the command is within a batch script, so the caret must be escaped.

    command | findstr win%%^^lose%% >> file.txt
    

    It is easier to simply enclose the string in quotes so you don't need to escape the caret.

    command | findstr "win%%^lose%%" >> file.txt