regex - How can I extract a percentage number without the "%" symbol from a string?
问题描述
-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?
解决方案
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.
推荐阅读
- python - AES Crypt 版本 2 问题
- c# - UI 图像在错误的位置实例化
- r - 图像到 R 中的 excel 电子表格
- java - 在 arraylist 问题中列出
- angular - Angular 8 获取请求:标头发送为 nulll
- python - Raspberry PI 多线上的 LED 矩阵?
- php - 从数组php中的数据库获取数据
- java - 如何将存储为小端字节数组的 uint16 转换为 int?
- flutter - 有没有办法同步获取文档目录?
- python - ValueError:模型未配置为计算精度。您应该将 `metrics=["accuracy"]` 传递给 `model.compile()` 方法