3

If I have a text file with:

MachineName    IPAddress
Computer1234   10.0.1.1
Computer1235   10.0.1.2
Computer1236   10.0.1.3

Once I grab the MachineName from the computer, how can I get the corresponding IPAddress from the text above?

The (bash?) script will be run on a Mac, and the text above can be reformatted and/or inserted into the script itself (about 110 computers)...

Jens
  • 69,818
  • 15
  • 125
  • 179
Bripakes
  • 33
  • 1
  • 4

2 Answers2

5

This is what awk is made for: search for fields by pattern and then do some action. The basic idea is

awk '/pattern/ {action}' file

In your case that would be

awk '/Computer1234/ { print $2 }' file

In fact, you could be more specific, using the general awk use case

awk 'condition { action }' file

with

awk '$1 == "Computer1234" { print $2 }' file

On a different note, converting host names to IP addresses is what name servers do. If this is more than playing around and needs to scale, you should insert that data into a name server's zone files, then use name service access tools like dig to query the address(es) associated with a host name.

Jens
  • 69,818
  • 15
  • 125
  • 179
1

Using grep makes it pretty straight forward.

grep 'Computer1234' text_file.txt | awk '{print $2}'

However we can do better and just use awk alone.

awk -v hostname='Computer1234' '$1 ~ hostname {print $2}' text_file.txt

-v var_name= is how you pass awk variables.

$1 ~ hostname looks to see if the first field contains a pattern that matches the hostname variable, if it does we print the ip!

A Brothers
  • 536
  • 2
  • 9