anmatika
anmatika

Reputation: 1701

Grep value between strings with regex

$ 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 '(?<=, )(.*)(?=%)'

Upvotes: 5

Views: 215

Answers (5)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Using :

s='Battery 0: Charging, 18%, 01:37:09 until charged'
res="${s#*, }"
res="${res%%%*}"
echo "$res"

Result: 18.

res="${s#*, }" removes text from the beginning to the first comma+space and "${res%%%*}" removes all text from end till (and including) the last occurrence of %.

Upvotes: 1

ashish_k
ashish_k

Reputation: 1581

Using awk:

 awk -F"," '{print $2+0}'

Using GNU sed:

sed -rn 's/.*\, *([0-9]+)\%\,.*/\1/p'

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133518

Could you please try following, written and tested in link https://ideone.com/nzSGKs

your_command | awk 'match($0,/Charging, [0-9]+%/){print substr($0,RSTART+10,RLENGTH-11)}'

Explanation: Adding detailed explanation for above only for explanation purposes.

your_command |                              ##Running OP command and passing its output to awk as standrd input here.
awk '                                       ##Starting awk program from here.
match($0,/Charging, [0-9]+%/){              ##Using match function to match regex Charging, [0-9]+% in line here.
  print substr($0,RSTART+10,RLENGTH-11)     ##Printing sub string and printing from 11th character from starting and leaving last 11 chars here in matched regex of current line.
}'

Upvotes: 2

dawg
dawg

Reputation: 103844

You can use sed:

$ acpi | sed -nE 's/.*Charging, ([[:digit:]]*)%.*/\1/p'
18

Or, if Charging is not always in the string, you can look for the ,:

$ acpi | sed -nE 's/[^,]*, ([[:digit:]]*)%.*/\1/p'

Upvotes: 1

anubhava
anubhava

Reputation: 785156

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

Upvotes: 4

Related Questions