Buster
Buster

Reputation: 444

How to filter CMD command results?

I am making a simple ping tool batch script. And I would like to filter the output the CMD gives, using the ping command. Normally the output of a ping would be like this:

C:\WINDOWS\system32>ping 8.8.8.8

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=21ms TTL=52
Reply from 8.8.8.8: bytes=32 time=25ms TTL=52
Reply from 8.8.8.8: bytes=32 time=19ms TTL=52
Reply from 8.8.8.8: bytes=32 time=17ms TTL=52

But I would like to filter out the size of the packets the ttl, and change the Reply text. So that it would look more like this:

C:\WINDOWS\system32>ping 8.8.8.8

Pinging 8.8.8.8 with 32 bytes of data:
Reply: time=21ms 

I found in this post that I should be able to do that with a awk -F argument, however trying that in my script just closes the CMD window on opening. How could I do what I want to do?

My script right now:

@ECHO OFF


:PING
cls & set /p address=Host to ping: 
@echo Started pinging at: %time%

ping %address%  /t  & echo. & pause. & goto :PING

Upvotes: 0

Views: 2761

Answers (1)

Compo
Compo

Reputation: 38719

Based upon your provided information, here's a quick example using FOR /F, as indicated in the comment section.

@Echo Off

:PingIt
ClS
Set /P "IP=Host to ping: "
Echo "%IP%"|"%__AppDir__%findstr.exe" "\"[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\"">NUL^
 ||GoTo PingIt
Echo Started pinging at: %TIME%
For /F "Tokens=1-7,9" %%G In (
    '""%__AppDir__%PING.EXE" %IP%|"%__AppDir__%findstr.exe" "ms$ data""'
)Do If "%%N"=="" (Echo(%%G %%H %%I %%J %%K %%L %%M)Else Echo Reply: time=%%N
Pause

The code includes a 'better than nothing' validation of your end user's input, before trying to use it as an IP Address. It also includes an optional Pause command, included only to show you the output before the cmd.exe window closes, (dependent upon your method of invoking the script).

Please note that the example does not cater for responses which fail the ping, e.g. Request timed out.. These cases are outside of the scope of your question so I have left it to you to deal with yourself.

Upvotes: 2

Related Questions