I need little help from the community:
I have these two lines in a large text file:
Connected clients: 42
4 ACTIVE CLIENTS IN LAST 20 SECONDS
How I ca开发者_高级运维n find, extract and assign the numbers to variables?
clients=42
active=4
SED, AWK, GREP? Which one should I use?
clients=$(grep -Po '^(?<=Connected clients: )([0-9]+)$' filename)
active=$(grep -Po '^([0-9]+)(?= ACTIVE CLIENTS IN LAST [0-9]+ SECONDS$)' filename)
or
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)
str='Connected clients: 42 4 ACTIVE CLIENTS IN LAST 20 SECONDS'
set -- $str
clients=$3
active=$4
If it's two lines, fine.
str1='Connected clients: 42'
str2='4 ACTIVE CLIENTS IN LAST 20 SECONDS'
set -- $str1
clients=$3
set -- $str2
active=$1
Reading two lines from a file may be done by
{ read str1; read str2; } < file
Alternately, do the reading and writing in AWK, and slurp the results into Bash.
eval "$(awk '/^Connected clients: / { print "clients=" $3 }
/[0-9]+ ACTIVE CLIENTS/ { print "active=" $1 }
' filename)"
you can use awk
$ set -- $(awk '/Connected/{c=$NF}/ACTIVE/{a=$1}END{print c,a}' file)
$ echo $1
42
$ echo $2
4
assign $1, $2 to appropriate variable names as desired
if you can directly assign using declare
$ declare $(awk '/Connected/{c=$NF}/ACTIVE/{a=$1}END{print "client="c;print "active="a}' file)
$ echo $client
42
$ echo $active
4
精彩评论