[英]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)?如何在没有百分比字符的情况下 grep 电池电量值 (18)?
This should do it but I'm getting an empty result:这应该可以,但我得到一个空结果:
acpi | grep -e '(?<=, )(.*)(?=%)'
Your regex is correct but will work with experimental -P
or perl mode regex option
in gnu grep
.您的正则表达式是正确的,但可以与gnu grep
实验性-P
或perl mode regex option
一起使用。 You will also need -o
to show only matching text.您还需要-o
来仅显示匹配的文本。
Correct command would be:正确的命令是:
grep -oP '(?<=, )\d+(?=%)'
However, if you don't have gnu grep
then you can also use sed
like this:但是,如果您没有gnu grep
那么您也可以像这样使用sed
:
sed -nE 's/.*, ([0-9]+)%.*/\1/p' file
18
Using awk
:使用awk
:
awk -F"," '{print $2+0}'
Using GNU sed
:使用GNU sed
:
sed -rn 's/.*\, *([0-9]+)\%\,.*/\1/p'
Could you please try following, written and tested in link https://ideone.com/nzSGKs您能否尝试在链接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.
}'
You can use sed
:您可以使用sed
:
$ acpi | sed -nE 's/.*Charging, ([[:digit:]]*)%.*/\1/p'
18
Or, if Charging
is not always in the string, you can look for the ,
:或者,如果Charging
并不总是在字符串中,您可以查找,
:
$ acpi | sed -nE 's/[^,]*, ([[:digit:]]*)%.*/\1/p'
s='Battery 0: Charging, 18%, 01:37:09 until charged'
res="${s#*, }"
res="${res%%%*}"
echo "$res"
Result: 18
.结果: 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 %
. res="${s#*, }"
删除从开头到第一个comma+space
文本,而"${res%%%*}"
删除从结尾到(并包括)最后一次出现的所有文本%
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.