deadcell4
deadcell4

Reputation: 6725

How to check if string contains more than one special character

I have this

if [[ ! $newstring == *['!'@#\$%^\&*()_+]* ]]
then
    echo Error - Does not contain One Special Character - $newstring
    i=$((i+1))
fi

Which checks if the string only has one single character from the bank, i want to check if it has more than one?

What would be the best way?

Upvotes: 1

Views: 3244

Answers (4)

Kannan Mohan
Kannan Mohan

Reputation: 1850

We can use tr to solve it.

$ string='Hello-World_12@$@#*&%)(!@#@#'

$ number=$(( $(tr -d '[[:alnum:]]' <<< "$string"|wc -m) - 1 ))

$ echo "We have $number of special characters"
$ 16

This should be short and faster.

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

grep can be useful to provide the match

grep -oP "^[^'\!'@#\$%^\&*()_+]*['\!'@#\$%^\&*()_+][^'\!'@#\$%^\&*()_+]+$"

test

$ echo "#asdfasdf234" | grep -oP "^[^'\!'@#\$%^\&*()_+]*['\!'@#\$%^\&*()_+][^'\!'@#\$%^\&*()_+]+$"

will match the string as

#asdfasdf234

$ echo "#asdf#asdf234" | grep -oP "^[^'\!'@#\$%^\&*()_+]*['\!'@#\$%^\&*()_+][^'\!'@#\$%^\&*()_+]+$"

will not match the string

The if construct can be

echo $newstring| grep -oP "^[^'\!'@#\$%^\&*()_+]*['\!'@#\$%^\&*()_+][^'\!'@#\$%^\&*()_+]+$"
if [[ $? -eq 0 ]] > /dev/null
then
    echo Error - Does not contain One Special Character - $newstring
    i=$((i+1))
fi

Here the regex

^[^'\!'@#\$%^\&*()_+]*['\!'@#\$%^\&*()_+][^'\!'@#\$%^\&*()_+]+$

matches all strings with exact one occurence of the special character

Upvotes: 0

AKS
AKS

Reputation: 17336

#!/bin/bash

a='!*@%6789'; 
if [[ `echo $a | sed "s/\(.\)/\1\n/g"|grep -c "[[:punct:]]"` -gt 1 ]]; then echo shenzi; else echo koba; fi

Upvotes: 0

Etan Reisner
Etan Reisner

Reputation: 81012

Either add a second class

if [[ "$newstring" != *['!'@#\$%^\&*\(\)_+]*['!'@#\$%^\&*\(\)_+]* ]]

or strip anything else out and check length

t="${newstring//[^!@#\$%^\&*()_+]}"
if [ ${#t} -lt 2 ]

Upvotes: 2

Related Questions