简体   繁体   中英

Match if variable has WORD repeated more than once

I have this variable:

>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

I am trying to create a conditional where it detects whether ge-0.0.3 is repeated more than 1 time in my variable $br_name

For example:

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

Bash's =~ is using extended 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

You can use grep -o to print only the matched phrase. Also use -F to make sure that it matches literal characters instead of a regex where . and - are special

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

For more complex patterns of course you can drop -F and write a proper regex for grep

simple word

If your word would be "easy", you can detect the occurrences count with:

echo "123 123 123" | sed "s/123 /123\n/g" | wc -l

In which the word is replace for the same but with \n and then wc count the lines

or you can try one of these:

complex

Since your word is "complex" or you will want a pattern, you will need regex:

script.sh

count=0

for word in $1; do
  if [[ "$word" =~ .*ge-0\.0\.3.* ]]
  then
    count=$(($count+1))
  fi
done

if [ "$count" -gt "1" ];
then
  echo "ge-0.0.3 is shown more than once"
else
  if [ "$count" -eq "0" ];
  then
    echo "ge-0.0.3 is not shown"
  else
    echo "ge-0.0.3 is shown once"
  fi
fi

execution

bash script.sh "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"

演示

grep

With grep you can get the ocurrence count

ocurrences=( $(grep -oE '(ge-0\.0\.3)' <<<$1) )
ocurrences_count=${#ocurrences[*]}
echo $ocurrences_count

在此处输入图像描述

Assuming you want to do a literal string match on whole words, not substrings, then this might be what you want:

$ if (( $(grep -oFw 'ge-0.0.3' <<<"$br_name" | wc -l) > 1 )); then echo 'yes'; else echo 'no'; fi
yes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM