Arale
Arale

Reputation: 39

How to test whether a string doesn't contain specified letters in bash

In a program I am writing I need to check whether a string contains characters not in another string e.g.:

if [ $string ?? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ]; then
    echo $string isnt alphanumeric
fi

or

if [ $string ?? "ABCDEGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"]; then
    echo $string isnt alphabetic
fi

Where ?? is the mystery operation.

Any help would be appreciated!

Upvotes: 1

Views: 1889

Answers (1)

glenn jackman
glenn jackman

Reputation: 246774

In bash, within [[...]], the == and != operators are pattern matching operators, so

validChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

if [[ $string != *["$validChars"]* ]]; then
    echo "$string does NOT contain any of $validChars"
fi

Ref: https://www.gnu.org/software/bash/manual/bash.html#index-_005b_005b


To test that a string ONLY contains characters in $validChars, we can use bash's extended pattern matching

if [[ $string == +(["$validChars"]) ]]; then
    echo "$string ONLY contains chars in $validChars"
fi
if [[ $string != +(["$validChars"]) ]]; then
    echo "string is empty or contains some character not in $validChars"
fi

Upvotes: 4

Related Questions