Reputation: 24248
I use the df
command in a bash script:
df . -B MB | tail -1 | awk {'print $4'} | grep .[0-9]*
This script returns:
99%
But I need only numbers (to make the next comparison).
If I use the grep
regex without the dot:
df . -B MB | tail -1 | awk {'print $4'} | grep .[0-9]*
I receive nothing. How to fix?
Upvotes: 24
Views: 125584
Reputation: 1317
You can use Perl style regular expressions as well. A digit is just \d
then.
grep -Po "\\d+" filename
-P Interpret PATTERNS as Perl-compatible regular expressions (PCREs).
-o Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
Upvotes: 0
Reputation: 11
Don't use more commands than necessary, leave away tail, grep and cut. You can do this with only (a simple) awk
PS: giving a block-size en print only de persentage is a bit silly ;-) So leave also away the "-B MB"
df . |awk -F'[multiple field seperators]' '$NF=="Last field must be exactly --> mounted patition" {print $(NF-number from last field)}'
in your case, use:
df . |awk -F'[ %]' '$NF=="/" {print $(NF-2)}'
output: 81
If you want to show the percent symbol, you can leave the -F'[ %]' away and your print field will move 1 field further back
df . |awk '$NF=="/" {print $(NF-1)}'
output: 81%
Upvotes: 1
Reputation: 11
function getPercentUsed() {
$sys = system("df -h /dev/sda6 --output=pcent | grep -o '[0-9]*'", $val);
return $val[0];
}
Upvotes: 1
Reputation: 195029
If you try:
echo "99%" |grep -o '[0-9]*'
It returns:
99
Here's the details on the -o
(or --only-matching
flag) works from the grep manual page.
Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line. Output lines use the same delimiters as input, and delimiters are null bytes if -z (--null-data) is also used (see Other Options).
Upvotes: 51
Reputation: 784918
No need to used grep here, Try this:
df . -B MB | tail -1 | awk {'print substr($5, 1, length($5)-1)'}
Upvotes: 1
Reputation: 53533
How about:
df . -B MB | tail -1 | awk {'print $4'} | cut -d'%' -f1
Upvotes: 1
Reputation: 38279
grep
will print any lines matching the pattern you provide. If you only want to print the part of the line that matches the pattern, you can pass the -o option:
-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
Like this:
echo 'Here is a line mentioning 99% somewhere' | grep -o '[0-9]+'
Upvotes: 9