BASH:在文本中查找数字 - >变量

时间:2011-01-18 22:17:51

标签: shell sed awk grep

我需要社区的帮助:

我在大文本文件中有这两行:

Connected clients: 42  
4 ACTIVE CLIENTS IN LAST 20 SECONDS  

如何查找,提取并将数字分配给变量?

clients=42
active=4

SED,AWK,GREP?我应该使用哪一个?

3 个答案:

答案 0 :(得分:4)

str='Connected clients: 42 4 ACTIVE CLIENTS IN LAST 20 SECONDS'

set -- $str
clients=$3
active=$4

如果是两行,那很好。

str1='Connected clients: 42'
str2='4 ACTIVE CLIENTS IN LAST 20 SECONDS'

set -- $str1
clients=$3
set -- $str2
active=$1

从文件中读取两行可以通过

完成
{ read str1; read str2; } < file

或者,在AWK中进行读写,并将结果粘贴到Bash中。

eval "$(awk '/^Connected clients: / { print "clients=" $3 }
             /[0-9]+ ACTIVE CLIENTS/ { print "active=" $1 }
            ' filename)"

答案 1 :(得分:4)

clients=$(grep -Po '^(?<=Connected clients: )([0-9]+)$' filename)
active=$(grep -Po '^([0-9]+)(?= ACTIVE CLIENTS IN LAST [0-9]+ SECONDS$)' filename)

clients=$(sed -n 's/^Connected clients: \([0-9]\+\)$/\1/p' filename)
active=$(sed -n 's/^\([0-9]\+\) ACTIVE CLIENTS IN LAST [0-9]\+ SECONDS$/\1/p' filename)

答案 2 :(得分:1)

你可以使用awk

$ set -- $(awk '/Connected/{c=$NF}/ACTIVE/{a=$1}END{print c,a}' file)
$ echo $1
42
$ echo $2
4

根据需要为适当的变量名分配$ 1,$ 2

如果你可以使用declare

直接分配
$ declare $(awk '/Connected/{c=$NF}/ACTIVE/{a=$1}END{print "client="c;print "active="a}' file)
$ echo $client
42
$ echo $active
4