Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: Find number in text -> variable

Tags:

grep

shell

sed

awk

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 can find, extract and assign the numbers to variables?

clients=42
active=4

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

like image 747
Adrian Avatar asked Jan 20 '23 17:01

Adrian


1 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)
like image 194
Dennis Williamson Avatar answered Jan 30 '23 21:01

Dennis Williamson