我有這個輸出:
>echo $br_name
srxa wan-a1 br-wan3-xa1 0A:AA:DD:C1:F1:A3 ge-0.0.3 srxa wan-a2 br-wan3-xa2 0A:AA:DD:C1:F2:A3 ge-0.0.3
我正在嘗試創建一個條件,它檢測ge-0.0.3在我的變數“$br_name”中是否重復超過 1 次
例如:
if [[ $br_name has ge-0.0.3 repeated more than one time ]]
then
echo "ge-0.0.3 is shown more than once"
else
:
fi
uj5u.com熱心網友回復:
Bash=~正在使用擴展的 RE。
[Bash-5.2] % check() { local s='(ge-0\.0\.3.*){2,}'; [[ "$1" =~ $s ]] && echo yes || echo no; }
[Bash-5.2] % check 'xxx'
no
[Bash-5.2] % check 'ge-0.0.3'
no
[Bash-5.2] % check 'ge-0.0.3 ge-0.0.3 '
yes
[Bash-5.2] % check 'ge-0.0.3 ge-0.0.3 ge-0.0.3 '
yes
uj5u.com熱心網友回復:
簡單的詞
如果您的話“簡單”,您可以通過以下方式檢測出現次數:
echo "123 123 123" | sed "s/123 /123\n/g" | wc -l
其中單詞被替換為相同但用\n然后wc計算行數
或者您可以嘗試其中一種:
grep
使用 grep 您可以獲得出現次數
ocurrences=( $(grep -oE '(ge-0\.0\.3)' <<<$1) ) ocurrences_count=${#ocurrences[*]} echo $ocurrences_count
uj5u.com熱心網友回復:
您可以使用
grep -o僅列印匹配的短語。還用于-F確保它匹配文字字符而不是正則運算式,其中.和-是特殊的if [[ $(echo $br_name | grep -Fo ge-0.0.3 | wc -l) -gt 1 ]]; then echo "ge-0.0.3 is shown more than once" else echo "only once" fi當然,對于更復雜的模式,您可以洗掉
-F并撰寫適當的正則運算式grep
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468968.html
