How do I nest a Windows FOR command in the 'set' of another FOR command?
I have a directory of configuration files. If a file contains a 'STATE = 3' entry, I want to extract the value of the TCPHOST entry and the name of the file. There are a lot of nested quotes in that so I used "usebackq" but without success:
c:\config>For /F "usebackq tokens=1,3 delims==: " %A in (`FOR /F "tokens=1 delims= " %P IN ('FINDSTR /M /I /R /C:"*STATE.*=.*3" * ') DO ('FINDSTR /I /S /C:"TCPHOST" %P')`) do (echo '%A|http://%B')
`) was unexpected at this time.
I have replaced the inner "FOR" command with a simple "DIR" and the results are technically correct (albeit meaningless) - I display the first and third tokens of the output.
Am I trying to do something impossible with these commands. (I am aware that I could probably write a bat file or PowerShell script but that's not my question.)
I was able to get the result that (I guess) you want, sticking to CMD, but breaking your monster command into multiple steps, with an intermediate file:
copy/y nul %temp%\out1.txt
FOR /F "tokens=1 delims= " %P IN ('FINDSTR /M /I /R /C:"STATE.*=.*3" * ') DO (FINDSTR /I /S /C:"TCPHOST" %P) >> %temp%\out1.txt
For /F "tokens=1,3 delims==: " %A in (%temp%\out1.txt) do (echo '%A^|http://%B')
del %temp%\out1.txt
I can’t figure out exactly why you got the error you got, but here are a few possible show-stoppers in your code:
-
"*STATE.*=.*3"
should be"STATE.*=.*3"
(or maybe".*STATE.*=.*3"
) because starting a regular expression with*
is invalid. -
DO ('FINDSTR /I /S /C:"TCPHOST" %P')
should beDO (FINDSTR /I /S /C:"TCPHOST" %P)
— the command afterDO
shouldn’t be in quotes. -
echo '%A|http://%B'
should beecho '%A^|http://%B'
(to get a literal|
rather than trying to pipeecho '%A
intohttp://%B'
) or maybeecho %A^|http://%B
(to avoid getting single quotes in the output — or do you want them?).