Re: [Linuxcommand-discuss] regular expressions in scripts
Brought to you by:
bshotts
|
From: William S. <wes...@co...> - 2002-08-09 22:02:12
|
On Wednesday 07 August 2002 04:21 am, Mertens Bram wrote:
> Hi,
>
> I'm trying to figure out how to perform a regular expression as the
> expression for an if-statement:
>
> I want it to either strip the trailing / if it's present or add it if it
> isn't.
>
> I thought the second would be easier since it wouldn't require creating
> a substring but I can't get it to work! I've tried for over an hour
> yesterday using every expression I could think of!
>
> Here's the if-statement:
> if [ ! "expr $2 match'.*/$'" ]; then
> TARGET_DIR=$2/
> echo "target dir changed to ${TARGET_DIR}"
> fi
>
> Some of the things I tried are
> [ ! $2 = .*/$ ]
> [ ! $2 : .*/$ ]
> [ ! "expr $2 ='.*/$'" ]
> [ ! "expr $2 match'.*/$'" ]
> [ ! "${2}" = "*/$" ] and [ ! "${2}" = ".*/$" ]
> with no quotes, double quotes, single quotes, brackets, etc.
> I've also tried with and without spaces after the ":" or "=" or
> "match"...
>
> Part of the problem is that I don't know what the correct regular
> expression is. Sometimes you ".*" sometimes it's just "*" (not to
> mention quotes and brackets!)
>
> I found something about pattern matching in a reference book called
> "Linux in a nutshell" but I can't find examples.
>
> Should anybody have this book it's in table 4-17 (at least in my
> translated version). These are the 4 possibilities:
> ${VAR#PATTERN}
> ${VAR##PATTERN}
> ${VAR%PATTERN}
> ${VAR%%PATTERN}
>
> If I understand it correctly I would need something like:
> ${${2}%/} but I get "bad substitution"
>
> Any suggestions?
>
> TIA
${VAR%PATTERN} will match the shortest part of PATTERN and will delete it
from the end of the string. To remove a trailing "/" you could do something
like this:
foo=/some/kind/of/path/
echo ${foo%/}
/some/kind/of/path
You were close in your example above. Try ${2%/}
bash does not really have regular expression matching, just wildcards. Some
other commands that are useful for this kind of problem include:
basename
dirname
egrep
--
||||| William Shotts, Jr. (bshotts AT panix DOT com)
||||| Be a Linux Commander! Follow me to http://linuxcommand.org
|