bash脚本在变量处使用cut命令并将结果存储在另一个变量中

时间:2021-01-02 19:31:13

I have a config.txt file with IP addresses as content like this

我有一个config.txt文件,IP地址就像这样的内容

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 ip address 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.

我是初学者,抱歉这个问题,但我自己也找不到。

2 个解决方案

#1


32  

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的问题,这里是你脚本的修订版本。

##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}

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读取行,文件中的读取行通常被认为更有效...完成<$ {file}模式。

I hope this helps.

我希望这有帮助。

#2


5  

You can avoid the loop and cut etc by using:

您可以使用以下命令来避免循环和剪切等:

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

However it would be better if you post a snippet of your config.txt

但是,如果您发布config.txt的片段会更好

#1


32  

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的问题,这里是你脚本的修订版本。

##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}

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读取行,文件中的读取行通常被认为更有效...完成<$ {file}模式。

I hope this helps.

我希望这有帮助。

#2


5  

You can avoid the loop and cut etc by using:

您可以使用以下命令来避免循环和剪切等:

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

However it would be better if you post a snippet of your config.txt

但是,如果您发布config.txt的片段会更好