我有一個現有的基本腳本,無論我是 grep cat 還是 dog,我都只需要從中獲取SERIAL的值。像這樣:
# grep dog | <additional commands>
123456789
腳本 = 動物.sh
#!/bin/bash
ANIMAL=$1
case "${ANIMAL}" in
dog)
echo ""
echo "${ANIMAL} animal is chosen"
SERIAL=123456789
;;
cat)
echo ""
echo "${ANIMAL} animal is chosen"
SERIAL=987654321
;;
*)
echo ""
echo "wrong parameter applied"
exit 1
;;
esac
到目前為止,我已經嘗試過這些,但是我仍在嘗試研究如何繼續或修剪其他輸出
[ec2-user@ip-192-168-100-101 ~]$ grep dog -A 3 animals.sh
dog)
echo ""
echo "${ENV} animal is chosen"
SERIAL=123456789
[ec2-user@ip-192-168-100-101 ~]$
uj5u.com熱心網友回復:
如果awk是您的選擇,請嘗試:
awk '
/dog/ {f = 1} # if the line matches "dog", set a flag
f && /SERIAL/ { # if the flag is set and the line matches "SERIAL"
sub(".*SERIAL=", "") # remove substring before the number
print # print the result
exit
}
' animals.sh
輸出:
123456789
如果您更喜歡grep解決方案,這里有一個替代方案:
grep -Poz 'dog[\s\S] ?SERIAL=\K\d ' animals.sh
解釋:
- 該
-P選項啟用PCRE正則運算式。 - 該
-o選項告訴 grep 僅列印匹配的子字串 - 該
-z選項將記錄分隔符設定為空字符,從而啟用跨行的模式匹配。
關于正則運算式:
dog[\s\S] ?SERIAL=dog匹配一個介于兩者之間的最短字串(包括換行符)SERIAL=。\K告訴正則運算式引擎從匹配的模式中丟棄之前的匹配。它可以在之前清除匹配的模式\K。\d匹配將作為結果列印的數字序列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/447761.html
下一篇:Centos7下載及安裝
