[英]Grep value between strings with regex
$ acpi
Battery 0: Charging, 18%, 01:37:09 until charged
如何在沒有百分比字符的情況下 grep 電池電量值 (18)?
這應該可以,但我得到一個空結果:
acpi | grep -e '(?<=, )(.*)(?=%)'
您的正則表達式是正確的,但可以與gnu grep
實驗性-P
或perl mode regex option
一起使用。 您還需要-o
來僅顯示匹配的文本。
正確的命令是:
grep -oP '(?<=, )\d+(?=%)'
但是,如果您沒有gnu grep
那么您也可以像這樣使用sed
:
sed -nE 's/.*, ([0-9]+)%.*/\1/p' file
18
使用awk
:
awk -F"," '{print $2+0}'
使用GNU sed
:
sed -rn 's/.*\, *([0-9]+)\%\,.*/\1/p'
您能否嘗試在鏈接https://ideone.com/nzSGKs 中進行跟蹤、編寫和測試
your_command | awk 'match($0,/Charging, [0-9]+%/){print substr($0,RSTART+10,RLENGTH-11)}'
說明:為以上添加詳細說明,僅供說明之用。
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.
}'
您可以使用sed
:
$ acpi | sed -nE 's/.*Charging, ([[:digit:]]*)%.*/\1/p'
18
或者,如果Charging
並不總是在字符串中,您可以查找,
:
$ acpi | sed -nE 's/[^,]*, ([[:digit:]]*)%.*/\1/p'
使用bash :
s='Battery 0: Charging, 18%, 01:37:09 until charged'
res="${s#*, }"
res="${res%%%*}"
echo "$res"
結果: 18
。
res="${s#*, }"
刪除從開頭到第一個comma+space
文本,而"${res%%%*}"
刪除從結尾到(並包括)最后一次出現的所有文本%
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.