how do I pipe to the "for" command?
How do I pipe to the for command. So instead of
C:\asd>ipconfig | findstr "Address" >a
C:\asd>for /f "tokens=15" %f in (a) do @echo %f
192.168.1.3
I would like to be able to do it on one line.
C:\asd>ipconfig | findstr "Address" | for /f "tokens=15" %f do @echo %f
do was unexpected at this time.
Although it doesn't appear to be documented, you can pipe to the command inside the FOR command. I first learned about it from this example:
SC query | FOR /F "tokens=2" %%i IN ('FIND /I "SERVICE_NAME"') DO @ECHO %%i
This modified version of your code works:
C:\>ipconfig | for /f "tokens=14" %f in ('findstr "Address"') do @echo %f
192.168.x.x
192.168.y.y
You can also use "more" inside the FOR command, as described in this answer, to parse input piped in from an arbitrary command:
C:\>ipconfig | findstr "Address" | for /f "tokens=14" %f in ('more') do @echo %f
192.168.x.x
192.168.y.y
Looking at the documentation for for
(run for /?
to see it), I don't think for /f
will read from a pipe. The only valid sources are file-set, "string", and 'command'.
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
You could put the command inside the for
like this:
for /f "tokens=15" %f in ('ipconfig ^| findstr "Address"') do @echo %f
192.168.x.x
192.168.y.y
(thanks to neurolysis for pointing out it has to be ^|
and not just |
)
Or you could try putting ipconfig | findstr "Address"
in a separate batch script and calling:
for /f "tokens=14" %f in ('ipaddresses') do @echo %f
(assuming you called the script ipaddresses
).
Or you could use for
to do the work of findstr
too, like this:
for /f "tokens=2,14" %i in ('ipconfig') do @if %i==Address. @echo %j
192.168.x.x
192.168.y.y
it's not quite the same because it won't match IPv6 addresses, but something along those lines could work.
Also note that I changed tokens=15
to tokens=14
. I think the last field on the line is token 14. Works for me anyway.