Do you know of a better or easier way of using sed or Bash to replace from the last occurrence of a regex match from the end of a line without using rev
?
Here is the rev
way to match the third from last occurrence of the letter 's' – still forward matching, yet utilizing rev
to match from the last character.
echo "a declaration of sovereignty need no witness" | rev | sed 's/s/S/3' | rev
a declaration of Sovereignty need no witness
Update -- a generalized solution based on Cyruses answer:
SEARCH="one"
OCCURRENCE=3
REPLACE="FOUR"
SED_DELIM=$'\001'
SEARCHNEG=$(sed 's/./[^&]*/g' <<< "${SEARCH}")
sed -r "s${SED_DELIM}${SEARCH}((${SEARCHNEG}${SEARCH}){$((${OCCURRENCE}-1))}${SEARCHNEG})\$${SED_DELIM}${REPLACE}\1${SED_DELIM}" <<< "one one two two one one three three one one"
Note: To be truly generic it should escape regex items from the LHS.