Nslookup command line with A record IP as sole output

nslookup was never really intended for scripted use. You really want to use dig instead, which with the +short option produces machine-readable output according to the query parameters.

dig +short myip.opendns.com @resolver1.opendns.com

This is a good usecase for awk.

nslookup myip.opendns.com resolver1.opendns.com | awk -F': ' 'NR==6 { print $2 } '

Here we are piping to awk, delimiting by ": " and then only outputting the second delimited field of line 6.


Nslookup with A record IP as sole output

Assuming you are using Windows, this can be done using a simple one line command.

From the command line:

for /f "skip=4 usebackq tokens=2" %a in (`nslookup myip.opendns.com resolver1.opendns.com`) do echo %a > ip.txt

From a batch file:

for /f "skip=4 usebackq tokens=2" %%a in (`nslookup myip.opendns.com resolver1.opendns.com`) do echo %%a > ip.txt

Notes:

  • The public IP address is stored in a file (ip.txt).
  • The above does not require non standard windows commands like PowerShell, .Net or awk.

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • for /f - Loop command against the results of another command.
  • nslookup - Lookup IP addresses on a NameServer.