I'd like to use reasoning similar to the approach below, which in this case uses a number (starting at 1) to replace the nth occurrence, but we want something in reverse order, that is, last, last 2nd, last 3rd, last 4th and so on.
QUESTION: Is it possible to use sed to substitute last, last 2nd, last 3rd, last 4th (and so on) match (occurrence)? If yes, how?
NOTE: Any approach that converts these numeric values to something specific to sed
(a bash function, for example) is also acceptable. Using sed
in conjunction with some command commonly found on Linux is also an acceptable answer. However, it is necessary that we can also use sed
with files by adding -i
.
EXAMPLE
sed -z 's/<TARGET>/<REPLACE>/<NTH_MATCH>'
EXAMPLE USE I
read -r -d '' FILE_CONTENT << 'HEREDOC'
BEGIN
askdjisoadjsadmsadjnasjndnsakjn
jkjkljkljklkljlkjkljl
jkljkljkljkklj
hjkhjkhkjh
jkjkljkljklkljlkjkljl
jkljkljkljkklj
hjkhjkhkjh
jdsjhfbjdhs
jdsjhfbjdhs
jdsjhfbjdhs
jdsjhfbjdhs
jdsjhfbjdhs
jdsjhfbjdhs
END
HEREDOC
SOURCE="${FILE_CONTENT:6:-3}"
echo "${SOURCE}" | sed -z 's/jkjkljkljklkljlkjkljl\njkljkljkljkklj\nhjkhjkhkjh/hbeuhyewuhdfjh\nfdsjisfdjiusdfijuhsfiuhsfdihusfdjhiusfdjkh\nkjhsfdjkfjkhsfdjknh/2'
EXAMPLE USE II
read -r -d '' FILE_CONTENT << 'HEREDOC'
BEGIN
askdjisoadjsadmsadjnasjndnsakjn
jkjkljkljklkljlkjkljl
jkljkljkljkklj
hjkhjkhkjh
jkjkljkljklkljlkjkljl
jkljkljkljkklj
hjkhjkhkjh
jdsjhfbjdhs
jdsjhfbjdhs
jdsjhfbjdhs
jdsjhfbjdhs
jdsjhfbjdhs
jdsjhfbjdhs
END
HEREDOC
SOURCE="${FILE_CONTENT:6:-3}"
echo "${SOURCE}" | sed -z 's/jdsjhfbjdhs/IReplacedTheLast4th/4'
**TIP:** This approach can be used to replace the last match (occurrence) -> `sed -z 's/\(.*\)<TARGET>/\1<REPLACE>/'`.
**Thanks!**