2

I have this following line

scalar TestDmaMac4.sink.udpApp[0]   throughput:last     11730.559888477

I want to extract only 11730 out of this line, how can I do it with grep? I want to ignore the number after decimal point and only need digits before decimal point.

(Note: there is a {space}{tab} sequence separating each of udpApp[0], throughput:last and the number beginning 11730.)

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
Linux-Fan85
  • 23
  • 1
  • 4

3 Answers3

0

The bellow regexp will match any floating number in the format [0-9].[0-9] and will return the integer part of this floating number.

$ a="scalar TestDmaMac4.sink.udpApp[0] throughput:last 11730.559888477"
$ egrep -o '[0-9]+[.][0-9]' <<<"$a" |egrep -o '[0-9]+[^.]'  #First grep will isolate the floating number , second grep will isolate the int part.
11730
$ perl -pe 's/(.*?)([0-9]+)(\.[0-9]+.*)/\2/' <<<"$a"  #using the lazy operator ?
11730
$ sed -r 's/(.*[^0-9.])([0-9]+)(\.[0-9]+.*)/\2/' <<<"$a"  #sed does not have lazy operator thus we simulate this with negation
11730

For the sake of testing, i also tried above regexp in a different string with floatting number at different position without a leading space:

$ c="scalar throughput:last11730.559888477 TestDmaMac4.sink.udpApp[0]"
$ egrep -o '[0-9]+[.][0-9]' <<<"$c" |egrep -o '[0-9]+[^.]'
11730
$ perl -pe 's/(.*?)([0-9]+)(\.[0-9]+.*)/\2/' <<<"$c"
11730
$ sed -r 's/(.*[^0-9.])([0-9]+)(\.[0-9]+.*)/\2/' <<<"$c"
11730
0
l='scalar TestDmaMac4.sink.udpApp[0]   throughput:last     11730.559888477'
read -r -a a <<<"$l"
dc -e "${a[-1]}dX10r^dsa*la/p"

echo "$l" | perl -lane 'print/\d+(?=\.\d+$)/g'

result

11730
-2

Using Grep:

grep -o " [0-9]\{1,\}"

To Test:

echo "scalar TestDmaMac4.sink.udpApp[0] throughput:last 11730.559888477" | grep -o " [0-9]\{1,\}"

results:

11730
Norm
  • 9
  • 2