0

I have a list file that contains server names and IP addresses. How would I go about reading each line, and separating it into two variables that will be used to complete other commands?

Sample in MyList:

server01.mydomain.com 192.168.0.23
server02.testdomain.com 192.168.0.52

intended script

#!/bin/bash
MyList="/home/user/list"
while read line
do
   echo $line #I see a print out of the hole line from the file
   "how to make var1 ?" #want this to be the hostname
   "how to make var2 ?" #want this to be the IP address
   echo $var1
   echo $var2
done < $MyList

2 Answers 2

4

Just pass multiple arguments to read:

while read host ip
do
    echo $host
    echo $ip
done

If there is a third field you don't want to read into $ip, you can create a dummy variable for that:

while read host ip ignored
do
    # ...
done
Sign up to request clarification or add additional context in comments.

2 Comments

monkey wrench, what happens if there is a third field which I do not want added to var2?
Updated my answer. This is all covered in the documentation that I linked, by the way.
0
#!/bin/bash
#replacing spaces with comma. 
all_entries=`cat servers_list.txt | tr ' ' ','`
for a_line in $all_entries
   do
        host=`echo $a_line | cut -f1 -d','`
        ipad=`echo $a_line | cut -f2 -d','`
        #for a third fild
        #field_name=`echo $a_line | cut -f3 -d','`
        echo $host
        echo $ipad
   done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.