Code:
#!/bin/bash
# -------------------------------------------------------------------------- #
# Examples before and after:
# 01.foo.bar.ext -> foo.bar.01.ext
# 10.foo.txt -> foo.10.txt
# 9.foo.bar.fubar.cfg -> foo.bar.fubar.9.cfg
# -------------------------------------------------------------------------- #
tstStr01="01.foo.bar.ext"
echo -e "\nOriginal string: $tstStr01"
echo -e "\n - Using Sed - - - - - - -\n"
echo $tstStr01 | sed -r 's/(01)\.(.*)\.(ext)/\2.\1.\3/'
echo -e "\n - Using Bash - - - - - - -\n"
strPrefix=${tstStr01%%.*} # get prefix
strSuffix=${tstStr01##*.} # get suffix
tmp1=${tstStr01%.*} ; strRest=${tmp1#*.} # get "rest"
echo "$strRest.$strPrefix.$strSuffix" # rebuild
As shown in the above code snippet using sed and back-referencing is a simple task but using bash internals it needs multiple steps to accomplish the same result.
Questions (about the bold part):
- Is it at all possible to use back-referencing when using parameter expansion? Haven't been able to find anything on-line about this.
- Is there a shorter, possibly more elegant way to do this?
Just to make sure: I'm looking for a bash internal solution and _not_ for an awk, perl, sed, etc solution.