1

I have a string "12G 39G 24% /dev" . I have to extract the value '24'. I have used the below regex

grep '[0-9][0-9]%' -o

But I am getting output as 24%. I want only 24 as output and don't want '%' character. How to modify the regex script to extract only 24 as value?

4 Answers4

1

The most common way not to capture something is using look-around assertions: Use it like this

grep -oP '[0-9][0-9](?=%)'

It's worth noting that GNU grep support the -P option to enable Perl compatible regex syntax, however it is not included with OS X. On Linux, it will be available by default. A workaround would be to use ack instead.

But I'd still recommend to use GNU grep on OS X by default. It can be installed on OSX using Homebrew with the command brew grep install


Also, see How to match, but not capture, part of a regex?

Resethel
  • 21
  • 5
0

One option would be to just grep again for the digits:

grep -o '[0-9][0-9]%' | grep -o '[0-9][0-9]'

However, if you want to accomplish this with a single regex, you can use the following:

grep -Po '[0-9]{2}(?=%)'

Note the -P option in this case; vanilla grep doesn't seem to support the (?=%) "look-around" part.

johnmastroberti
  • 847
  • 2
  • 12
0

You can use sed as an alternative:

sed -rn 's/(^.*)([[:digit:]]{2})(%.*$)/\2/p' <<< "12G 39G 24% /dev"

Enable regular expressions with -r or -E and then split the line into 3 sections represented through parenthesis. Substitute the line for the second section only and print.

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18
0

Use awk:

awk '{print $3+0}'

The value you seek is in the third field, and adding a zero coerces the string to a number, so % is removed.

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37