Home:ALL Converter>Match if variable has WORD repeated more than once

Match if variable has WORD repeated more than once

Ask Time:2022-05-01T08:11:44         Author:nickcrv06

Json Formatter

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

Author:nickcrv06,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72073102/match-if-variable-has-word-repeated-more-than-once
JRichardsz :

simple word\nIf your word would be "easy", you can detect the occurrences count with:\necho "123 123 123" | sed "s/123 /123\\n/g" | wc -l\n\nIn which the word is replace for the same but with \\n and then wc count the lines\nor you can try one of these:\n\nCount occurrences of a char in a string using Bash\nHow to count number of words from String using shell\n\ncomplex\nSince your word is "complex" or you will want a pattern, you will need regex:\n\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\nhttps://linuxconfig.org/advanced-bash-regex-with-examples\n\nscript.sh\ncount=0\n\nfor word in $1; do\n if [[ "$word" =~ .*ge-0\\.0\\.3.* ]]\n then\n count=$(($count+1))\n fi\ndone\n\nif [ "$count" -gt "1" ];\nthen\n echo "ge-0.0.3 is shown more than once"\nelse\n if [ "$count" -eq "0" ];\n then\n echo "ge-0.0.3 is not shown"\n else\n echo "ge-0.0.3 is shown once"\n fi\nfi\n\nexecution\nbash 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"\n\n\ngrep\nWith grep you can get the ocurrence count\nocurrences=( $(grep -oE '(ge-0\\.0\\.3)' <<<$1) )\nocurrences_count=${#ocurrences[*]}\necho $ocurrences_count\n\n",
2022-05-01T01:43:53
pynexj :

Bash's =~ is using extended RE.\n[Bash-5.2] % check() { local s='(ge-0\\.0\\.3.*){2,}'; [[ "$1" =~ $s ]] && echo yes || echo no; }\n[Bash-5.2] % check 'xxx'\nno\n[Bash-5.2] % check 'ge-0.0.3'\nno\n[Bash-5.2] % check 'ge-0.0.3 ge-0.0.3 '\nyes\n[Bash-5.2] % check 'ge-0.0.3 ge-0.0.3 ge-0.0.3 '\nyes\n",
2022-05-01T02:46:20
phuclv :

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\nif [[ $(echo "$br_name" | grep -Fo ge-0.0.3 | wc -l) -gt 1 ]]; then\n echo "ge-0.0.3 is shown more than once"\nelse\n echo "only once"\nfi\n\nFor more complex patterns of course you can drop -F and write a proper regex for grep",
2022-05-01T01:45:22
yy