Find the answer to your Linux question:
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 ...
  1. #1
    Just 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

  2. #2
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    for newer bash
    Code:
    # s="A wasp is mean and ugly"
    # [[ $s =~ ugly ]] && echo "yes"
    yes
    see my sig to learn bash.

  3. #3
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    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:
    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"
    fi
    I hope that helps!
    DISTRO=Arch
    Registered Linux User #388732

  4. #4
    Just 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!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...