簡體   English   中英

帶有正則表達式的字符串之間的 Grep 值

[英]Grep value between strings with regex

$ acpi

Battery 0: Charging, 18%, 01:37:09 until charged

如何在沒有百分比字符的情況下 grep 電池電量值 (18)?

這應該可以,但我得到一個空結果:

acpi | grep -e '(?<=, )(.*)(?=%)'

您的正則表達式是正確的,但可以與gnu grep實驗性-Pperl 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'

使用

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM