LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash: back-referencing / shuffle string content using internals (https://www.linuxquestions.org/questions/programming-9/bash-back-referencing-shuffle-string-content-using-internals-4175486039/)

druuna 11-27-2013 07:30 AM

Bash: back-referencing / shuffle string content using internals
 
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.

grail 11-27-2013 10:56 AM

How about:
Code:

#!/bin/bash

regex='([^.]+)\.(.*)\.(.{3})'

[[ "$1" =~ $regex ]] && echo "${BASH_REMATCH[2]}.${BASH_REMATCH[1]}.${BASH_REMATCH[3]}"

This gave me your required output for the 3 examples (Note: the sed will not :) )

druuna 11-27-2013 11:48 AM

Quote:

Originally Posted by grail (Post 5071500)
How about:
Code:

#!/bin/bash

regex='([^.]+)\.(.*)\.(.{3})'

[[ "$1" =~ $regex ]] && echo "${BASH_REMATCH[2]}.${BASH_REMATCH[1]}.${BASH_REMATCH[3]}"

This gave me your required output for the 3 examples

That's a really good alternative. Readable and compact.
Quote:

(Note: the sed will not :) )
Yeah..... Added the examples after I reread the finished post and forgot about the fixed ext part in the code.

Thanks!


All times are GMT -5. The time now is 08:32 PM.