Hello, I have a file path such as: /path/to/whatever/30 and I want to get the number off the end. My problem is that there might be other numbers in the path and the last number can be 1 or 2 digits. I tried something like:
sed 's/.*\(\/[0-9]\{1,2\}\).*/\1/'
which seems to work fine for single digit numbers, but if it is 10, I only get a 0. Also that might fail if there is a number in the path. Is there something simpler than using sed for this situation? Any ideas?
I would not use that trick in good conscience, those bash parameter substitution tricks are nice in the absence of any other tool (read sed, awk, basename), but they are cryptic, hard to read and to remember what they mean. I pity the person who would have to maintain a bash program that utilizes parameter substitution extensively.
$ s="/a/b/c"
$ time (for((i=1;i<=200;i++));do s=${s##*/};done)
real 0m0.018s
user 0m0.016s
sys 0m0.000s
$ time (for((i=1;i<=200;i++));do s=$(basename "$s");done)
real 0m4.611s
user 0m6.831s
sys 0m2.515s
Interesting, I stand corrected. I revise my earlier statement to say: those POSIX parameter substitution tricks are nice in the absence of any other tool (read sed, awk, basename) or the presence of a need for optimization. Although python is much slower than C/C++, I would use python over C/C++ anyday, unless there is a compelling reason to invest the extra developer hours to squeeze out the extra CPU seconds.
The other day I spent close to 20 minutes debugging a script riddled with those parameter substitution tricks, for a script that is run once every night and finishes in few milliseconds, so no obvious optimization needs. I estimate I would've spent closer to 5 minutes debugging if the author of that used sed instead.