0

I am trying to print out a number next to a string that I search (using shell script).

For ex., my file contains a line

arg[30] = -Xmx4096m

I search the file with string Xmx and I need the output of next digits attached to the string and nothing else is needed in the output. How can I achieve this?

1

If your version of grep supports PCRE mode, you can use grep -Po 'Xmx\K\d+'

Ex.

echo 'F arg[30] = -Xmx4096m' | grep -Po 'Xmx\K\d+'
4096
  • unfortunately not, but thanks for the answer. – Gautham K Oct 20 '16 at 5:09
2
sed -n 's/.*Xmx\([0-9]\+\).*/\1/p' filename

Explanation:

  • sed -n makes sed only print output when told (by p)
  • s/<p1>/<p2>/p search for <p1> and replace with <p2>. then print line
  • .*Xmx\([0-9]\+\).* any string with Xmx followed by digits. the digits are "captured".
  • \1 the first captured group.

In human words: search for lines containing Xmx followed by digits. Take note of the digits. Discard everything but keep the digits. Print the digits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.