2012-03-15 44 views
13

我有一个的config.txt文件,IP地址,这样bash脚本使用剪切命令的变量,结果存储在另一个变量

10.10.10.1:80 
10.10.10.13:8080 
10.10.10.11:443 
10.10.10.12:80 

我想平在每个IP地址内容文件

#!/bin/bash 
file=config.txt 

for line in `cat $file` 
do 
    ##this line is not correct, should strip :port and store to ip var 
    ip=$line|cut -d\: -f1 
    ping $ip 
done 

我是一个初学者,对于这样的问题抱歉,但我找不到自己。

+0

'for cat in cat file'将会运行两次......一次用'line = cat'和一次用'line = file'。我不认为这就是你想要的。 – FatalError 2012-03-15 18:44:17

回答

30

awk的解决方案是我会用什么样的一个片段可能会更好,但如果你想用bash了解你的问题,这里是你的脚本的修订版本。

##config file with ip addresses like 10.10.10.1:80 
#!/bin/bash -vx 
file=config.txt 

while read line ; do 
    ##this line is not correct, should strip :port and store to ip var 
    ip=$(echo "$line" |cut -d\: -f1) 
    ping $ip 
done < ${file} 

你可以写你的顶线

for line in $(cat $file) ; do ... 

您需要的命令替换$(...)获取某个文件

读线分配到$ IP值通常被认为与更高效while read line ... done < ${file}模式。

我希望这会有所帮助。

+0

+ 1效率更高,但更安全:'for $( 2012-03-15 18:54:07

+0

@yourmother,请注意在这里使用变量的引号:对于保护值中的空白至关重要。 – 2012-03-15 18:55:47

+2

注意ip可以用'ip = $ {line %%:*}'提取,而不必调用echo | cut。 – 2012-03-15 18:56:37

4

可以避开环路,并通过使用切等:

awk -F ':' '{system("ping " $1);}' config.txt 

但是,如果您发布的config.txt