Reputation: 33
-InternalBattery-0 (id=7405667) 100%; charged; 0:00 remaining present: true
I want to do egrep -ow (regex)
on the above string and get only 100
of 100%
and nothing else. How can I do that?
Upvotes: 0
Views: 756
Reputation: 236420
You can use pcregrep to check if the string has one to three digits preceded by a boundary and look ahead for a percentage character:
pcregrep --color '\b(?:100|[1-9]?\d)(?=%)' file.txt
To install pcreg you can download it from here. To install it using macOS terminal check this link
Upvotes: 0
Reputation: 84579
sed
with a backreferece to reinsert the digits before the percent sign in the general substitution form is probably a bit more doable than grep
. For example you can use:
sed -E 's/^[^)]+\)\s+([0-9]+)%.*$/\1/'
Which matches one of more characters from the beginning that are not ')'
, then a literal ')'
and then matches any amount of whitespace. A capture group begins capturing digits up to the next '%'
with remaining characters to end of line discarded. The first backreference \1
is used to replace the whole line with what was captured between the (...)
in ([0-9+)%
.
Example Use/Output
$ echo "-InternalBattery-0 (id=7405667) 100%; charged; 0:00 remaining present: true" |
sed -E 's/^[^)]+\)\s+([0-9]+)%.*$/\1/'
100
Awk Solution
Since in the comment you mention you are attempting this in Apple Script (which I know little about), then perhaps a straight-forward awk
solution that simply loops to find the field that contains the '%'
character and than chops-off everything from '%'
to the end of the field, prints the result and exits, e.g.
$ echo "-InternalBattery-0 (id=7405667) 100%; charged; 0:00 remaining present: true" |
awk '{ for( i=1; i<=NF; i++) if ($i ~ /%/) { sub(/%.*$/,"",$i); print $i; exit }}'
100
That way you can, again, use the '%'
character to identify the proper field in your string of text and then simply remove it, and anything that follows, and be confident that you have the correct result if '%'
only appears once in your line of input.
Give it a try and let me know if you have further questions.
Upvotes: 2