Carlos Sanchez
Carlos Sanchez

Reputation: 61

Regular expression to trim from a line, get the number in the line

Need to get the total memory info from the unix system from proc mem info: right now this command gets the right line for me: cat /proc/meminfo | grep "MemTotal" But this returns the whole line:

MemTotal:      1024984 kB

I need to trim that line even further into:

1024984 kB

So far this is the full command I am using but the second part doesn't seem to work:

cat /proc/meminfo | grep "MemTotal" | grep -E -o "([0-9])"

I thought that the second grep would at least return the numeric part, however its not returning anything at all.

Can anyone help me correct this? Thanks.

Upvotes: 0

Views: 205

Answers (2)

Sundeep
Sundeep

Reputation: 23697

awk is better suited here, for all lines matching MemTotal, print the 2nd and 3rd column

$ grep 'MemTotal' /proc/meminfo
MemTotal:        1024984 kB
$ awk '/MemTotal/{print $2,$3}' /proc/meminfo
1024984 kB


With grep, if PCRE is available use variable-length lookbehind:

$ grep -oP 'MemTotal:\h+\K.*' /proc/meminfo
1024984 kB

Upvotes: 4

choroba
choroba

Reputation: 242323

Weird, for me, it returns

8
0
8
4
9
0
4

That's because [0-9] only matches one digit. You need a + to match at least one. You can also drop the parentheses, they serve no purpose here.

grep MemTotal /proc/meminfo | grep -E -o '[0-9]+'

Upvotes: 0

Related Questions