bash 脚本在变量中使用 cut 命令并将结果存储在另一个变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9725897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash script use cut command at variable and store result at another variable
提问by CodingYourLife
I have a config.txtfile with IP addresses as content like this
我有一个以 IP 地址作为内容的config.txt文件,如下所示
10.10.10.1:80
10.10.10.13:8080
10.10.10.11:443
10.10.10.12:80
I want to ping every ipaddress in that file
我想ping那个文件中的每个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
I'm a beginner, sorry for such a question but I couldn't find it out myself.
我是初学者,很抱歉提出这样的问题,但我自己找不到。
回答by shellter
The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.
我将使用 awk 解决方案,但如果您想了解 bash 的问题,这里是您脚本的修订版。
#!/bin/bash -vx
##config file with ip addresses like 10.10.10.1:80
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}
You could write your top line as
你可以把你的顶线写成
for line in $(cat $file) ; do ...
You needed command substitution $( ... )
to get the value assigned to $ip
您需要命令替换$( ... )
来获取分配给 $ip 的值
reading lines from a file is usually considered more efficient with the while read line ... done < ${file}
pattern.
从文件中读取行通常被认为使用该while read line ... done < ${file}
模式更有效。
I hope this helps.
我希望这有帮助。
回答by anubhava
You can avoid the loop and cut etc by using:
您可以使用以下方法避免循环和切割等:
awk -F ':' '{system("ping " );}' config.txt
However it would be better if you post a snippet of your config.txt
但是,如果您发布 config.txt 的片段会更好