Monday, March 28, 2016

Replacing Nth Occurrence from End of Line via Sed

SEARCH="one" 
SEARCHNEG=$(sed 's/./[^&]*/g' <<< "${SEARCH}")
OCCURRENCE=3 
REPLACE="FOUR" 
SED_DELIM=$'\001'  
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"

No comments:

Post a Comment