tags:

views:

1195

answers:

3
+3  Q: 

Groovy grep a word

I wanted to grep for java process and then find the max heap memory used. I tried this

def ex =['sh','-c','ps -aef | grep Xmx']; String str = ex.execute().text;

while str has something like " java -Xmx1024M /kv/classes/bebo/ -Xms512M" How do I extract the value 1024M. I was planning to user java regex but thought someone might know a cool way in groovy.

A: 

In Java:

String ResultString = null;
Pattern regex = Pattern.compile("-Xmx(\\d+M)");
Matcher regexMatcher = regex.matcher(str);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group(1);
}
Jan Goyvaerts
A: 

If all you want is the value after Xmx, you could have that returned to you from the ex:

def ex =['sh','-c',"ps -aef | grep Xmx | sed -e 's/^.*Xmx\([0-9]*[mM]*\) *$/\1/'"]; 
String str = ex.execute().text;

The sed command will transform the output of ps into just the bit that comes out of ps before returning.

+3  A: 

Here's a groovy version that doesn't need the grep (or the sed :) :

("ps -aef".execute().text =~ /.*-Xmx([0-9]+M).*/).each { full, match -> println match }
Ted Naleid