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?
CodePudding user response:
To specify a literal search string, use the /C flag.
dir /A D:\path | findstr /C:"mykeyword"
CodePudding user response:
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. (To question-closers: My real very big aim is not related with this specific question and that my real very big aim is different should not be the reason to close this question.)
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 works.
(Though, in other words "how can escape special characters when using findstr within in ('""') question remains as a mystery.)
