[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] How to extract matching suffix pattern in bash?
From: |
Dan Douglas |
Subject: |
Re: [Help-bash] How to extract matching suffix pattern in bash? |
Date: |
Wed, 13 Mar 2013 22:22:53 -0500 |
User-agent: |
KMail/4.8.3 (Linux/3.4.6-pf+; KDE/4.8.3; x86_64; ; ) |
On Wednesday, March 13, 2013 08:09:46 PM Eric Blake wrote:
> On 03/13/2013 08:04 PM, Chet Ramey wrote:
> > On 3/13/13 6:21 PM, Peng Yu wrote:
> >> Hi,
> >>
> >> ${parameter%word} remove matching suffix pattern. I need something
> >> extract only the matching suffix which is to be not available
> >> according to bash manual. Do I miss anything?
> >
> > This is totally untested, but should be fairly self-explanatory, and is
> > portable to any Posix shell:
> >
> > suffix_pattern=whatever
> > prefix=${string%$suffix_pattern}
> > suffix=${string##$prefix}
>
> Except that it isn't robust if pattern contains globs:
>
> $ foo='a.*b'
> $ prefix=${foo%b}
> $ suffix=${foo##$prefix}
> $ echo "$suffix"
>
> $ echo "$prefix"
> a.*
>
> A more robust solution might involve counting the length of prefix,
> creating a string consisting of that many '.', and chopping off that
> that instead of risking expansion of the prefix turning into an
> unexpected glob match.
>
Quote the "$prefix". The pattern removal expansions nest just fine too.
Example in my last message.
--
Dan Douglas