2016-08-16 75 views
0

我有一个包含服务器名称和IP地址的列表文件。 我将如何阅读每一行,并将它分成两个变量,用于完成其他命令?Bash脚本:如何从一个字符串中创建两个变量?

在样品MYLIST:

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

意脚本

#!/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 

回答

4

只是多个参数传递给read

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

如果你不想给第三场读入$ip,可以为此创建一个虚拟变量:

while read host ip ignored 
do 
    # ... 
done 
+0

猴子扳手,如果有,我不想加入到VAR2第三场会发生什么? – cwheeler33

+0

更新了我的答案。顺便说一下,这些都是我链接的文档中的内容。 –

+0

真的很酷...谢谢! – cwheeler33

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 
相关问题