'How can find exact match with findstr in for of windows batch
What the only thing I want to do is in a windows batch, to get output of a dir command with findstr.
If I knew this was the most complicated thing in life, I wouldn't try.
What I did is, first, write my command that I need its output:
dir /A D:\path | findstr mykeyword
But actually I need exact match of "keyword", so I found this:
https://stackoverflow.com/a/39235594/2536614
So, my command is now:
dir /A D:\path | findstr "\<mykeyword\>"
I have tried it and the output is what I want.
Then, how do I get its output in a batch file? Of course, the intuitive tries don't work. It must be complicated. So, I found this:
https://stackoverflow.com/a/10131068/2536614
A loop just to set a variable. Anyway, this brings another complication. Now I can not write "\<mykeyword\>" correctly, escaping the special characters, within, first ' then ", in For command, as the anwser suggests.
I have tried this:
For /F %%A in ('"dir /A %path_to_look% | findstr ""\\^<mykeyword\\^>"""') do set res1=%%A
This returns nothing. res1 is empty.
So, how can I find exact match with findstr, but within For command?
Solution 1:[1]
My solution has been using ^| instead of | only.
This makes it possible to use only ' instead of '" inside in().
So now I could write findstr "" without need of escaping " character, which was the only thing I was trying to find.
So,
before:
For /F %%A in ('"dir /A %path_to_look% | findstr ""\<mykeyword\>"""') do set res1=%%A
Supposedly " could be escaped as "" but this code did not work.
So,
after:
For /F %%A in ('dir /A %path_to_look% ^| findstr "\<mykeyword\>"') do set res1=%%A
This does work.
(Though, in other words "how can escape special characters when using findstr within in ('""') question remains as a mystery.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aschipfl |
