[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How to match pattern in bash?
From: |
Micah Cowan |
Subject: |
Re: How to match pattern in bash? |
Date: |
Tue, 22 Feb 2011 20:03:39 -0800 |
User-agent: |
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101208 Thunderbird/3.1.7 |
On 02/22/2011 07:24 PM, Peng Yu wrote:
> Suppose that I have a variable $x, I want to test if the content of $x
> match the pattern 'abc*'. If yes, then do something. (The operator ==
> doesn't match patterns, if I understand it correctly.)
>
> Is there such a build-in feature in bash? Or I have to rely on some
> external program such as perl to test the pattern matching?
Bash provides a few ways to do this that I can think of.
One portable way (the one I generally use), is to take advantage of the
fact that you can strip prefixes or suffixes from variables if they
match some specified pattern. This is portable to all POSIX-compliant sh
implementations. (Edit just before send-off: so is Eric Blake's.)
If the wildcard matches as a prefix of the variable, then it will no
longer compare equal to the variable (and will, otherwise).
test "x${var}" != "x${var##abc*}"
(Of course, for examples like yours where they just end in a *, the * is
unnecessary for the pattern, and you can just check for a prefix of
"x${var##abc}").
Bash's special builtin [[ ]] syntax also provides both wildcards, and
(much more powerful) extended regexes (roughly similar to Perl regexes;
they're what egrep uses).
Wildcards:
[[ $var == abc* ]]
Regex:
[[ $var =~ ^abc.* ]]
--
HTH,
Micah J. Cowan
http://micah.cowan.name/