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
2009-09-24 20:42:58
+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
2009-09-24 20:43:53
I'm nitpicking, but you don't need to quote $var.
Idelic
2009-09-25 16:03:41
+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
2009-09-24 20:52:24
+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
2009-09-24 20:55:19
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
2009-09-24 21:24:26
A:
[[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"
glenn jackman
2009-09-25 03:15:19
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
2009-09-28 12:02:45