Recent Articles

Bash Aliases
Most shells have some provision for aliases. Aliases can assign default behavior to a command...

Personal Dictionary For Ispell
Ispell works well, but it has to be the most confused project I've ever seen. I started looking into this because I got tired of seeing the same common words pop up for correction...


09.28.05


Bash In-process Regular Expressions

By A.P. Lawrence

Bash acquired in-process regular expressions in version 3.0, but I never noticed, probably because most of the machines I'm using are Bash 2.05b.

As I'm not necessarily in a position to upgrade any old box I happen to be working on, I tend to stick to the stuff that will work anywhere, which often means piping out to grep for a regular expression test.

However, should you have an environment where you can depend on this feature being present, in-process regexes obviously avoid firing up another process for grep and are much more neat to write or read.

The syntax is Perlish, using "=~". You also have access to sub-matches: $BASH_REMATCH is the string matched, ${BASH_REMATCH[1]} is the first parenthesided match, and so on. So, we can do:


if [[ "$input" =~ 'foo(.*)' ]]
then
echo $BASH_REMATCH is what I wanted
echo but just ${BASH_REMATCH[1]}
fi


and other more interesting tasks.

Set 'nocaseglob' for case insensitivity. The return value for these is 0 for a match, 1 for no match, and (how thoughtful) 2 if the expression is syntactically incorrect, so watch out for the other side of that "if" - a non-zero return might mean you screwed up your pattern.


About the Author:
Originally published at APLawrence.com

About LinuxDeveloperNews
Get the lastest information on current changes in the Linux Development World.

LinuxDeveloperNews is brought to you by:

SecurityConfig.com NetworkingFiles.com
NetworkNewz.com WebProASP.com
DatabaseProNews.com SQLProNews.com
ITcertificationNews.com SysAdminNews.com
LinuxDeveloperNews.com WirelessProNews.com
CProgrammingTrends.com DevWebPro.com


-- LinuxDeveloperNews is an iEntry, Inc. publication --
iEntry, Inc. 2549 Richmond Rd. Lexington KY, 40509
2005 iEntry, Inc.  All Rights Reserved  Privacy Policy  Legal

archives | advertising info | news headlines | free newsletters | comments/feedback | submit article

LinuxDeveloperNews News Archives About Us Feedback LinuxDeveloperNews Home Page About Article Archive News Downloads WebProWorld Forums Jayde iEntry Advertise Contact