Results 1 to 4 of 4
Using Bash
Okay... so I get a variable to be assigned a string. That string, for example, could either be "A wasp is fat and funny" or "A wasp is ...
- 08-10-2008 #1Just Joined!
- Join Date
- Apr 2008
- Posts
- 18
[SOLVED] How To... String...
Using Bash
Okay... so I get a variable to be assigned a string. That string, for example, could either be "A wasp is fat and funny" or "A wasp is mean and ugly".
How can I check the variable (called $wasp) to see if the string contains fat or contains mean as wasp may be bee or bunny sometimes too so I only want to check for that particular word found in the variable.
Thanks!
Mark
- 08-10-2008 #2Linux User
- Join Date
- Aug 2006
- Posts
- 458
for newer bash
see my sig to learn bash.Code:# s="A wasp is mean and ugly" # [[ $s =~ ugly ]] && echo "yes" yes
- 08-11-2008 #3
So to go into a bit more depth:
There is a tool called a regular expression. A regular expression (aka regex) basically allows you to match a string against a pattern of some sort. That pattern could be something literal (for instance, "fat"), or it could be a pattern of possible values (for instance, "three a's, then some number of spaces, then an exclamation point").
So what ghostdog is proposing is to match the string against the regex "ugly". The match will only return true if the pattern "ugly" appears in the string.
For a description of regular expressions, you can read this:
http://tldp.org/LDP/abs/html/x16044.html
In newer versions of Bash, you can do pattern matching on strings by using the "=~" operator, as shown by ghostdog.
Now, because your regular expression is a literal one, regexes may be a bit of overkill. Another option is to simply look for the first occurrence of the desired substring. The way to do this in Bash is:
I hope that helps!Code:pos=$(expr index "$string" "ugly") if [ "$pos" -eq "-1" ]; then echo "Ugly does not appear in the string" else echo "Ugly appears in the string" fiDISTRO=Arch
Registered Linux User #388732
- 08-11-2008 #4Just Joined!
- Join Date
- Apr 2008
- Posts
- 18
Thank you both very much for the feedback. I think, while the regex is overkill, it seems a bit more simple to look at and, when you know what it is, to know what's going on there. I'll go with that one. Tested and works great. Again, thank you both very much!


