Reputation: 33
After trawling through S.O. I've managed to piece together my function so it works, but I don't understand something about it. I'm basically trying to ensure that a file I want to use doesn't have double quotes in it. I've used findstr with the /m option which is returning the filename.
When I run the command from the cmd line it works with this:
findstr /V /L /m "\"" filename.txt
When filename has no double quotes it returns the filename, if it does have double quote it returns blank / null /whatever. Exactly what I want.
So I wanted to capture this result in a variable, using a solution on this website. I've discovered this works:
setlocal enabledelayedexpansion
set test=
for /F %%a in ('findstr /V /L /m ^"^\^"^" filename.txt') do (@set test=!test! %%a)
echo %test%
So my question: My search string needs to be escaped so goes from:
"\""
and becomes:
^"^\^"^"
but I don't understand why I have to do that. Can anybody explain?
Upvotes: 2
Views: 111
Reputation: 70943
To answer your question, the reason why your search string needs to be escaped (^
escaped) is ... none. In your case you search string does not need to be escaped.
@echo off
setlocal enableextensions disabledelayedexpansion
for /f "delims=" %%a in ('
findstr /l /m /v "\"" *.txt
') do echo %%a
You need the \"
escape because the findstr
argument handling (more here) but the ^"
scaping is not required.
But there are some cases where the ^
quote scaping is needed. The reason for the escaping in those cases is that the command inside the for /f
is executed in a separate cmd
instance. This started instance could (or not) include its own set of quotes
cmd /c " ...... "
and the quotes in your command could interfere in the cmd
parsing of the command to execute.
But if you escape the quotes (cmd
escaping, that is ^"
), they will not be parsed as closing/opening quotes, but as a literal without a special meaning for the cmd
parser, so they could be hadled later.
Upvotes: 1