Reputation: 1
I'm recent member to this board and batch file programming in general---hello!
For several days I tried the following script with mixed success:
@Echo OFF
FOR /f "tokens=3 delims=^:^(" %%G In ('PING "hostname.com"') DO (Echo %%G)
The purpose of the script is to ping a host and parse out the number (N) in (N% loss), from the Ping summary. The script does that, but instead of a number, I get "N% loss),", and not just the integer. I'm curious why this happens and how to make the script output only the integers of the percentage and no other characters. This batch file is running under Win7
Upvotes: 0
Views: 102
Reputation: 79983
FOR /f "tokens=3 delims=:(%%" %%G In ('PING "hostname.com"') DO (Echo %%G)
There's no need to escape virtually any characters in a delims
specifier, EXCEPT for %
which is escaped by doubling - caret (^
) doesn't work.
Oh - and why?
If the line is parsed including ONLY (
and :
as delimiters, then the line
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
has tokens
Packets
Sent = 4, Received = 4, Lost = 0
0% loss),
Upvotes: 2
Reputation: 4750
The parens are causing problems for you. But before we get to that... what you have just happens to be working as much as it is because there are not lines following the one you are interested in that have a ":" in them. I would discriminate by using FIND so that we only examine lines with the word "loss" (case insensitive). The "usebackq" is necessary because we are using quotes in the command. The "SET Scratch" lines below get rid of the parens.
@Echo OFF
FOR /f "usebackq tokens=3* delims==" %%G In (`PING hostname.com ^| FIND /I "loss"`) DO SET Scratch=%%H
SET Scratch=%Scratch:(=%
SET Scratch=%Scratch:)=%
FOR /f "tokens=2" %%G In ('echo.%Scratch%') DO SET Percent=%%G
ECHO.%Percent:~0,-1%
Upvotes: 2