Bripakes Bripakes - 1 year ago 73
Bash Question

how to select a value from a second column using a shell script?

If I have a text file with:

MachineName IPAddress

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)...

Answer Source

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


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

If you prefer a fully portable shell solution:

while read name ip; do
  if test "$name" = Computer1234; then
    echo $ip
done < file
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download