Sunday, July 10, 2022

[SOLVED] Extract specific number from command outout

Issue

I have the following issue.

In a script, I have to execute the hdparm command on /dev/xvda1 path. From the command output, I have to extract the MB/sec values calculated.

So, for example, if executing the command I have this output:

/dev/xvda1:
 Timing cached reads:   15900 MB in  1.99 seconds = 7986.93 MB/sec
 Timing buffered disk reads: 478 MB in  3.00 seconds = 159.09 MB/sec

I have to extract 7986.93 and 159.09.

I tried:

  1. grep -o -E '[0-9]+', but it returns to me all the six number in the output
  2. grep -o -E '[0-9]', but it return to me only the first character of the six values.
  3. grep -o -E '[0-9]+$', but the output is empty, I suppose because the number is not the last character set of outoput.

How can I achieve my purpose?


Solution

To get the last number, you can add a .* in front, that will match as much as possible, eating away all the other numbers. However, to exclude that part from the output, you need GNU grep or pcregrep or sed.

grep -Po '.* \K[0-9.]+'

Or

sed -En 's/.* ([0-9.]+).*/\1/p'


Answered By - Socowi
Answer Checked By - Candace Johnson (WPSolving Volunteer)