views:

1148

answers:

8

say a string might be like "a b '' c '' d", how can I check that there is single/double quote and space contained in the string?

+1  A: 

How about an approach similar to:

$ A="some string"; echo $A | grep \  | wc -l
1
$ A="somestring"; echo $A | grep \  | wc -l
0

?

Grzegorz Oledzki
+3  A: 
string="a b '' c '' d"
if [ "$string" == "${string//[\' ]/}" ]
then 
   echo did not contain space or single quote
else
   echo did contain space or single quote
fi
Paul
+6  A: 
case "$var" in  
     *\ * )
           echo "match"
          ;;
       *)
           echo "no match"
           ;;
esac
Steve B.
I'm nitpicking, but you don't need to quote $var.
Idelic
+2  A: 

The portable way to do this is with grep:

S="a b '' c '' d"
if echo $S | grep -E '[ "]' >/dev/null
then
  echo "It's a match"
fi

...a bit ugly, but guaranteed to work everywhere.

alex tingle
+4  A: 

You can use regular expressions in bash:

string="a b '' c '' d"
if [[ "$string" =~ \ |\' ]]    #  slightly more readable: if [[ "$string" =~ ( |\') ]]
then
   echo "Matches"
else
   echo "No matches"
fi
Dennis Williamson
A: 
function foo() {
    echo "String: $*"
    SPACES=$(($#-1))
    echo "Spaces: $SPACES"
    QUOTES=0
    for i in $*; do
        if [ "$i" == "'" ]; then
            QUOTES=$((QUOTES+1))
        fi
    done
    echo "Quotes: $QUOTES"
    echo
}

S="string with spaces"
foo $S
S="single' 'quotes"
foo $S
S="single '' quotes"
foo $S
S="single ' ' quotes"
foo $S

yields:

String: string with spaces
Spaces: 2
Quotes: 0

String: single' 'quotes
Spaces: 1
Quotes: 0

String: single '' quotes
Spaces: 2
Quotes: 0

String: single ' ' quotes
Spaces: 3
Quotes: 2
ezpz
A: 
[[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"
glenn jackman
A: 

I do wonder why nobody mentioned the [:space:] set. Usually your not only interested in detecting the space character. I often need to detect any white space, e.g. TAB. The "grep" example would look like this:

$ echo " " | egrep -q "[:space:]" && echo "Has no Whitespace" || echo "Has Whitespace"
Has Whitespace
$ echo "a" | egrep -q "[:space:]" && echo "Has no Whitespace" || echo "Has Whitespace"
Has no Whitespace
dz