Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I chain together filename modifiers in a bash shell?

I understand the modifiers # ## % %%, but I can't figure out if its possible to chain them together as you can in tcsh.

Example in tcsh

set f = /foo/bar/myfile.0076.jpg
echo $f:r:e
--> 0076

echo $f:h:t
--> bar

In bash, I'd like to know how to do something like:

echo ${f%.*#*.}

in one line.

My goal is to be able to manipulate filenames in various ways as and when needed on the command line. I'm not trying to write a script for one specific case. So if there is a way to chain these modifiers, or maybe there's another way, then I'd love to know. Thanks

like image 821
Julian Mann Avatar asked Feb 28 '11 20:02

Julian Mann


1 Answers

In bash, you can nest Parameter Expansions but only effectively in the word part in ${parameter#word}.

For example:

$ var="foo.bar.baz"; echo ${var%.*}
foo.bar
$ var="foo.bar.baz"; echo ${var#foo.bar}
.baz
$ var="foo.bar.baz"; echo ${var#${var%.*}}
.baz

To do what you want with pure parameter expansion, you need to have a temp var like so:

$ var="/foo/bar/myfile.0076.jpg"; tmp=${var#*.}; out=${tmp%.*}; echo $out
0076

However, if you're willing to use the set builtin then you could actually get access to all the fields in one go with some clever use of the search/replace Parameter Expansion like so:

$ var="/foo/bar/myfile.0076.jpg"; set -- ${var//[.\/]/ }; echo $4
0076
like image 195
SiegeX Avatar answered Oct 04 '22 21:10

SiegeX