Test If String Has Non Whitespace Characters in Bash

Test if string has non whitespace characters in Bash

You can use bash's regex syntax.

It requires that you use double square brackets [[ ... ]], (more versatile, in general).

The variable does not need to be quoted. The regex itself must not be quoted

for str in "         "  "abc      " "" ;do
if [[ $str =~ ^\ +$ ]] ;then
echo -e "Has length, and contain only whitespace \"$str\""
else
echo -e "Is either null or contain non-whitespace \"$str\" "
fi
done

Output

Has length, and contain only whitespace  "         "
Is either null or contain non-whitespace "abc "
Is either null or contain non-whitespace ""

Test if a string contains only whitespace and non-alphanumeric characters

Both your regex and syntax is incorrect. You need not use regex at all, just need glob for this:

checkStr() {
[[ $1 != *[a-zA-Z0-9]* ]]
}

This will return false if even one alphanumeric is found in the input. Otherwise true is returned.

Test it:

$> if checkStr 'abc'; then
echo "true case"
else
echo "false case"
fi
false case

$> if checkStr '=:() '; then
echo "true case"
else
echo "false case"
fi
true case

$> if checkStr '=:(x) '; then
echo "true case"
else
echo "false case"
fi
false case

How to check if a string has spaces in Bash shell

case "$var" in  
*\ * )
echo "match"
;;
*)
echo "no match"
;;
esac

Check if string is neither empty nor space in shell script

You need a space on either side of the !=. Change your code to:

str="Hello World"
str2=" "
str3=""

if [ ! -z "$str" -a "$str" != " " ]; then
echo "Str is not null or space"
fi

if [ ! -z "$str2" -a "$str2" != " " ]; then
echo "Str2 is not null or space"
fi

if [ ! -z "$str3" -a "$str3" != " " ]; then
echo "Str3 is not null or space"
fi

Bash get first N non white space characters

You can use grep:

grep '^[[:blank:]]*//' *.java

To search for a particular line # you can use sed:

sed -n '3s|^[[:blank:]]*//|&|p' file

Bash function for zero length string or with whitespace

You can use a regular expression:

if [[ $string =~ ^" "*$ ]]

or you can remove all the spaces before testing with -z:

if [[ -z "${string// /}" ]]

How do I check that a Java String is not all whitespaces?

Shortest solution I can think of:

if (string.trim().length() > 0) ...

This only checks for (non) white space. If you want to check for particular character classes, you need to use the mighty match() with a regexp such as:

if (string.matches(".*\\w.*")) ...

...which checks for at least one (ASCII) alphanumeric character.



Related Topics



Leave a reply



Submit