[wplug] Checking the extension of a file in a shell script

Eric Cooper ecc at cmu.edu
Fri May 12 19:58:02 EDT 2006


On Fri, May 12, 2006 at 07:43:30PM -0400, Brandon Kuczenski wrote:
> On Fri, 12 May 2006, Eric Cooper wrote:
> 
> >On Fri, May 12, 2006 at 03:53:17PM -0400, O'Connor, Michael P. wrote:
> >
> >>Does any one know how to check for a final character on a string
> >>(lets call it $file) I want to look to see if the last 2 chars are
> >>".C" this is csh,
> >
> >Check if "$file:e" (the extension) is equal to "C".
> >
> 
> Damn, that's pretty sweet.  Does bash do anything like that?  I've been 
> using echo $file | awk -F "." ' { print $NF }'

Yes, bash has even more powerful operations on variables.  For
example:
    ${foo: -2} expands to the last two characters of $foo
    (The white space is required.)

    ${foo%.*} expands to $foo without its extension

    ${foo#${foo%.*}} expands to just the extension

See the "Parameter Expansion" section of the man page.

-- 
Eric Cooper             e c c @ c m u . e d u


More information about the wplug mailing list