Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

How to check if a string has spaces in Bash shell

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?

question from:https://stackoverflow.com/questions/1473981/how-to-check-if-a-string-has-spaces-in-bash-shell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Edit:

For reasons obvious above, it's better to put the regex in a variable:

pattern=" |'"
if [[ $string =~ $pattern ]]

And quotes aren't necessary inside double square brackets. They can't be used on the right or the regex is changed to a literal string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...