Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Grep only the numbers from linux shell

I have an curl output as below and i need to grep only the numbers from that output.

Curl Output

<h1>JVM</h1><p>Free Memory:2144.78 MB Total Memory:3072.00 MB Max Memory:3072.00 MB</p><table border="0">

Grep Command

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 grep -o -i 'Max Memory:.*'  | awk  '{ print $3 }'

Output

MB</p><table

Expected Output : 3072.00

Similarly for Free Memory and Total Memory.

Please help

>Solution :

1st solution: With your shown samples, please try following in GNU grep.

grep -oP 'Total Memory:\K\S+' Input_file

OR in case you want to match exact digits which are coming for memory value then try following:

grep -oP 'Total Memory:\K\d+(?:\.\d+)?(?=\s)' Input_file

Explanation: Simple explanation would be, using GNU grep‘s -o and -P options firstly. To print only matched text and to enable PCRE regex flavor. Then in main grep program using regex to match Total Memory: to be searched followed by \K which means if previous match is found then forget the match. Then matching \S+ means match everything non-space(s) before a space comes which will catch value for Total memory.



2nd solution: In case you want to get 3 values in output for free memory, max and total ones then try following awk code. Written and tested in GNU awk.

awk -v RS='(Free Memory:|Total Memory:|Max Memory:)[^[:space:]]+' 'RT{sub(/.*:/,"",RT);print RT}' Input_file

NOTE: In case your output is not in an Input_file then you can use pipe to your previous command and then run this one.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading