Home > OS >  Set part of grep to variable
Set part of grep to variable

Time:07-19

mysqladmin proc status | grep "Threads"

Output:

Uptime: 2304  Threads: 14  Questions: 2652099  Slow queries: 0  Opens: 48791  Flush tables: 3  Open tables: 4000  Queries per second avg: 1151.08

I would like to set it so $mysqlthread would output 14 after running echo $mysqlthread

CodePudding user response:

Probably the easiest way is with Perl instead of grep.

mysqladmin proc status | perl -nle'/Threads: (\d )/ && print $1'

perl -n means "go through each line of input".

perl -l means "print a \n at the end of every print"

perl -e means "here is my program"

/Threads: (\d )/ means "match Threads: followed by one or more digits. And print $1 means "print the digits I found as denoted by the parentheses around \d .

CodePudding user response:

Using grep

$ mysqlthread=$(mysqladmin proc status | grep -Po 'Threads: \K\d ')
$ echo "$mysqlthread"
14

CodePudding user response:

There are many ways to solve this. This is one:

mysqladmin proc status | grep "Threads" | tr -s ' ' | cut -d' ' -f4

The tr command with flag -s is used to translate all multiple consecutive spaces into a single space. Then, cut command return the 4th field using a single space as delimiter.

The advantage of piping commands is that one can make this process interactively. And whenever you aren't sure which flag to use, the manual pages are there to help: man grep, man tr, man cut, etc.

CodePudding user response:

Add awk to split the output,

mysqlthread=$(mysqladmin proc status | grep "Threads" | awk '{print $4}')
  • Related