user2156699
user2156699

Reputation: 25

How to extract hostname within "ping -a" output?

I have to extract hostnames within "ping -a" outputs, but I can't figure it out, I was thinking about using regular expressions. I would need to extract characters between and  [ to get computername.windowsdomain. does it seem possible? I can't find good resources for batch regex online it's all about JS, PHP and .NET.

As I'm french the output of ping -a begins with:

Envoi d'une requête 'ping' sur XXXXXXXX.DOMAIN.NAME.com [127.0.0.1]

Upvotes: 1

Views: 1529

Answers (2)

Magoo
Magoo

Reputation: 80203

@ECHO OFF
SETLOCAL
FOR /f "delims=" %%i IN ('ping -n 1 -a 127.0.0.1^|find "["') DO CALL :sub %%i
ECHO hostname: %hostname%
ECHO domain: %domain%
ECHO whole chebang: %chebang%
GOTO :eof

:sub
SET hostname=%2
IF NOT %hostname:~0,1%==[ shift&GOTO sub
SET chebang=%1
FOR /f "tokens=1*delims=." %%a IN ("%1") DO SET hostname=%%a&SET domain=%%b
GOTO :eof

Should work for you. Variable names are not my area of expertise...

Upvotes: 0

Joey
Joey

Reputation: 354834

Batch files as such have no regex capabilities. There are options for filtering lines in text files or program outputs via findstr which uses its own interpretation of regular expressions which looks similar but is buggy and limited.

In any case, you can probably get away with something like the following:

set hostname=
for /f "skip=1 tokens=2" %%x in ('ping -n 1 -a so.me.i.p') do if not defined hostname set hostname=%x
echo %hostname%

Upvotes: 1

Related Questions