drjrm3
drjrm3

Reputation: 4728

allow for zero or more spaces in regex with grep

I have some files which may look like mem = 500, mem= 100, mem =256, or any combination of mem, whitespaces, =, and a number. If I assume there is no whitespace I can use:

grep -oP '(?<=mem=)[0-9]+'

but how do I change this to allow for white space between mem and =? Please keep in mind that I want to use grep here.

Upvotes: 0

Views: 7358

Answers (4)

Jotne
Jotne

Reputation: 41460

Here is an awk version:

awk -F" *= *" '{print $2}' file
500
100
256

If there are other line and you need mem only, do:

awk -F" *= *" '/mem/{print $2}' file
500
100
256

Upvotes: 0

dawg
dawg

Reputation: 104092

If you do not have GNU grep, you will need Perl, awk, sed etc.

Perl solution:

perl -lne 'print $1 if m/mem\s*=\s*(\d+)/;'

And sed:

sed -n 's/.*\mem *= *\([0-9]*\).*/\1/p'

awk:

awk -F'mem *= *' '{print $2}'

Upvotes: 0

mklement0
mklement0

Reputation: 440162

Try

grep -oP 'mem\s*=\s*\K[0-9]+' file

The \K simply drops everything matched so far, printing only the number.

This alternative to a look-behind assertion (such as (?<=mem=)) bypasses the latter's limitation that Tomalak mentions: look-behind assertions must be fixed-length.

Note: The nonstandard -P option - for PCRE (Perl-Compatible Regular Expression) support - requires GNU grep.

Upvotes: 5

nneonneo
nneonneo

Reputation: 179697

You can do two grep calls like so:

grep -oP 'mem *= *[0-9]+' | grep -oP '[0-9]+'

Upvotes: 0

Related Questions