I want to create a batch file that writes the local IP address on a txt file. When i run a batch file with this code (file path is wrong but that's not the problem):
ipconfig | find "IP Address" > \File.txt
I get the whole windows IP configuration (I changed some numbers and stuff with xxx to not show all info)
IP Address. . . . . . . . . . . . : 100.100.100.223
IP Address. . . . . . . . . . . . : 192.xxx.xxx.xxx
I want to write to a file only 100.100.100.223
.
I'm new to batch files and i really searched a lot and I'm really confused. (maybe i'm searching with wrong keywords).
Forgot to tell I'm using Windows XP (Because some of the answers doesn't work on XP).
Read the just written file's first line into a variable using the SET /P
command, then overwrite the file with that line using ECHO
:
ipconfig | find "IP Address" > \File.txt
< \File.txt SET /P first_ip=
ECHO %first_ip%> \File.txt
UPDATE (in answer to comments):
To extract just the IP address, you could use a FOR /F
loop like this:
ipconfig | find "IP Address" > \File.txt
< \File.txt SET /P first_ip=
FOR /F "delims=: tokens=2" %%I IN ("%first_ip%") DO (
ECHO %%I> \File.txt
)
A FOR /F
loop allows you to process text (a file or a string literal) line by line, splitting each line into fields (or tokens) based on the specified delimiter(s). You can read more about this command in the built-in help (FOR /?
). I'll only add that in this case the processed piece is a string literal (the value of first_ip
), the delimiter is set to :
, and the loop variable (%%I
) receives the 2nd token, which is an IP address.
Note that the space between :
and the IP is preserved, i.e. it becomes part of the token ( 100.100.100.223
) and, therefore, gets written to the file too. If you aren't very happy about it, you could use a subroutine to get rid of the space, like this:
ipconfig | find "IP Address" > \File.txt
< \File.txt SET /P first_ip=
FOR /F "delims=: tokens=2" %%I IN ("%first_ip%") DO (
CALL :MyEcho %%I
)
:: the following command is there merely to
:: avoid running (into) the subroutine again
GOTO :EOF
:MyEcho
ECHO %1> \File.txt
When the subroutine is called (CALL :MyEcho %%I
), the argument is passed along with the leading space. But when processing the subroutine's command line, that space is no longer seen as part of the value, because the argument is not quoted and so the parser sees merely an argument separated from the name with two spaces. Thus the %1
in the subroutine evaluates to the address without the leading space.
for /f "tokens=2 delims=:" %%a in ('ipconfig^|find "IPv4 Address"') do (
set ip=%%a
goto :BREAK
)
:BREAK
echo %ip: =% >ip.txt
If you are OK with powershell, try this:
powershell.exe -c "gwmi Win32_NetworkAdapterConfiguration | ? { $_.IPAddress -ne $null } | % {$_.ipaddress[0]}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With