[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] How to extract matching suffix pattern in bash?
From: |
Eric Blake |
Subject: |
Re: [Help-bash] How to extract matching suffix pattern in bash? |
Date: |
Wed, 13 Mar 2013 20:09:46 -0600 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20130219 Thunderbird/17.0.3 |
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.
--
Eric Blake eblake redhat com +1-919-301-3266
Libvirt virtualization library http://libvirt.org
signature.asc
Description: OpenPGP digital signature