1# from http://mywiki.wooledge.org/BashFAQ/021
2
3# The ${a/b/c} substitution is not POSIX compatible. Additionally, in
4# bash 3.x, quotes do not escape slashes. This causes screwed up
5# installation paths.
6#
7#     SLES 11, bash-3.2-147.9.13
8#     $ dirname="foo/bar"
9#     $ echo ${dirname//"foo/bar"/"omg/nei"}
10#     bar/omg/nei/bar
11#
12#     openSUSE 12.2, bash-4.2-51.6.1
13#     $ dirname="foo/bar"
14#     $ echo ${dirname//"foo/bar"/"omg/nei"}
15#     omg/nei
16#
17#     openSUSE 12.2, dash-0.5.7-5.1.2.x86_64
18#     $ dirname="foo/bar"
19#     $ echo ${dirname//"foo/bar"/"omg/nei"}
20#     dash: 2: Bad substitution
21#
22# Source this file into your bash scripts to make available
23# a replacement (the string_rep function) for this substitution
24# mess.
25#
26
27string_rep()
28{
29	# initialize vars
30	in=$1
31	unset out
32
33	# SEARCH must not be empty
34	test -n "$2" || return
35
36	while true; do
37		# break loop if SEARCH is no longer in "$in"
38		case "$in" in
39			*"$2"*) : ;;
40			*) break;;
41		esac
42
43		# append everything in "$in", up to the first instance of SEARCH, and REP, to "$out"
44		out=$out${in%%"$2"*}$3
45		# remove everything up to and including the first instance of SEARCH from "$in"
46		in=${in#*"$2"}
47	done
48
49	# append whatever is left in "$in" after the last instance of SEARCH to out, and print
50	printf '%s%s\n' "$out" "$in"
51}
52