Bripakes Bripakes - 17 days ago 7
Bash Question

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

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

Answer

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

If you prefer a fully portable shell solution:

while read name ip; do
  if test "$name" = Computer1234; then
    echo $ip
  fi
done < file
Comments