Renry
Renry

Reputation: 33

Set part of grep to variable

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

Upvotes: 0

Views: 104

Answers (4)

WeDBA
WeDBA

Reputation: 343

Add awk to split the output,

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

Upvotes: 0

sseLtaH
sseLtaH

Reputation: 11227

Using grep

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

Upvotes: 1

AlberNovo
AlberNovo

Reputation: 156

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.

Upvotes: 0

Andy Lester
Andy Lester

Reputation: 93676

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+.

Upvotes: 1

Related Questions