Home > Blockchain >  Batch findstr return only field value
Batch findstr return only field value

Time:03-27

How can I return only the value field from a command in batch?

ipconfig /all | findstr "Host Name"

Will return

Host Name . . . . . . . . . . . . : YOUR_HOSTNAME

But I only want the value, YOUR_HOSTNAME.

Also, if there are more than one line it would probably be best to get the first that matches.

CodePudding user response:

for /f "tokens=1*delims=:" %b in ( 'ipconfig /all ^| findstr /c:"Host Name"') do set "hostname=%c"
set "hostname=%hostname:~1%"

from the prompt. Change %b and %c to %%b and %%c to use within a batch file.

The caret escapes the pipe, telling cmd that the pipe is part of the command to be executed, not of the for.

The /c:"Host Name" makes findstrfind the precise stringHost Name. As you have it, findstrwould find *either*Host*or*Name`, which would deliver a hit on

Ethernet adapter VirtualBox Host-Only Network:
   Description . . . . . . . . . . . : VirtualBox Host-Only Ethernet Adapter

for instance.

To force the first match, append &goto label to the for command line and insert :label between the two lines.

CodePudding user response:

If you want the hostname, Windows already provides a program to give exactly that without any string parsing.

%__APPDIR__%\hostname.exe

Use it in a batch-file to set a variable.

FOR /F "delims=" %%A IN ('"%__APPDIR__%\hostname.exe"') DO (SET "THISHOST=%%~A")
ECHO THISHOST IS %THISHOST%

If you want to step up to .Net or PowerShell, there is:

[System.Net.Dns]::GetHostName()
  • Related