BASH: Find the number in the text & # 8594; variable

I need a little community help:

I have these two lines in a large text file:

Connected clients: 42 4 ACTIVE CLIENTS IN LAST 20 SECONDS 

How can I find, extract, and assign numbers to variables?

 clients=42 active=4 

SED, AWK, GREP? Which one should I use?

+4
source share
3 answers
 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) 
+4
source
 str='Connected clients: 42 4 ACTIVE CLIENTS IN LAST 20 SECONDS' set -- $str clients=$3 active=$4 

If it's two lines, great.

 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 can be done using

 { read str1; read str2; } < file 

Alternatively, read and write to AWK and split the results into Bash.

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

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 the corresponding variable names as desired

if you can directly assign use of the ad

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

Source: https://habr.com/ru/post/1336063/


All Articles