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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With