Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep value between strings with regex

Tags:

regex

grep

sed

awk

$ acpi

Battery 0: Charging, 18%, 01:37:09 until charged

How to grep the battery level value without percentage character (18)?

This should do it but I'm getting an empty result:

acpi | grep -e '(?<=, )(.*)(?=%)'
like image 646
anmatika Avatar asked Oct 11 '20 14:10

anmatika


People also ask

Can I use regex with grep?

The grep command (short for Global Regular Expressions Print) is a powerful text processing tool for searching through files and directories. When grep is combined with regex (regular expressions), advanced searching and output filtering become simple.

Can you use wildcards with grep?

grep itself doesn't support wildcards on most platforms.


1 Answers

Your regex is correct but will work with experimental -P or perl mode regex option in gnu grep. You will also need -o to show only matching text.

Correct command would be:

grep -oP '(?<=, )\d+(?=%)'

However, if you don't have gnu grep then you can also use sed like this:

sed -nE 's/.*, ([0-9]+)%.*/\1/p' file
18
like image 180
anubhava Avatar answered Sep 23 '22 12:09

anubhava