Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make GREP select only numeric values?

Tags:

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?

like image 995
user710818 Avatar asked Dec 06 '11 16:12

user710818


People also ask

How do I grep only numbers in a line?

grep -r -L "[^0-9 ]" . [^0-9 ] will match anything that doesn't contain digits or spaces (thought that would be fitting or else all files that contain spaces and number would be discarded).

How do I grep a number in a file?

The -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.

How do you exclude characters in grep?

By default, grep is case-sensitive. This means that the uppercase and lowercase characters are treated as distinct. To ignore the case when searching, invoke grep with the -i option. If the search string includes spaces, you need to enclose it in single or double quotation marks.


1 Answers

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).

like image 198
Kent Avatar answered Sep 29 '22 09:09

Kent