2
% x=abracadabra
% echo ${x//a/o}
obrocodobro

Hmph...

Is there a way to replace the last occurrence of a pattern using shell substitions (IOW, without rolling out sed, awk, perl, etc.)?

  • Nope there isn't – llua Feb 27 '18 at 2:41
  • @llua: dang ... – kjo Feb 27 '18 at 2:44
3

Note: this replaces a trailing occurrence - not quite the same as "the last occurrence"

From the Bash reference manual Section 3.5.3 Shell Parameter Expansion :

${parameter/pattern/string} 

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with ‘/’, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with ‘#’, it must match at the beginning of the expanded value of parameter. If pattern begins with ‘%’, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If the nocasematch shell option (see the description of shopt in The Shopt Builtin) is enabled, the match is performed without regard to the case of alphabetic characters. If parameter is ‘@’ or ‘’, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.

So

$ x=abracadabra
$ echo "${x/%a/o}"
abracadabro
1

You can do this with shell substitutions its just a bit tricky. You basically grab everything before the pattern insert your replacement and than grab everything after the pattern. For your example that would look like this:

    x=abracadabra
    echo "${x%a*}o${x##*a}"

EDIT: Or just do what steeldriver suggested in the comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.