Modifying sed to only change last occurrence.

I'm using sed to switch integers (one or more digits) to the other side of the ':' colon. For example: "47593:23421" would then be "23421:47593". The way it functions right now, it is messing my settings file to use with gnuplot. The current command is:

sed 's/\([0-9]*\):\([0-9]*\)/\2:\1/' out3 > plotted.p

How can I modify this to only change the very last occurrence in the text file?

What I often do is make the GNUplot script itself a BASH script, which I execute and feed the output into gnuplot's stdin, or a temporary file. Things which need to vary can be fed in via commandline parameters. A bit more flexible, and a lot more direct, than dozens of little fiddly sed things.

This'd be tricky even in awk, because of the way it needs to put back changes it made earlier... It would have no way of knowing when the end of file is coming, after all. The script that generates it in the first place might.

This is pretty simple using ed (assuming that there is only one pair of colon separated numbers on the last line in out3 that contains a colon and that there are no colons that don't have digits before and after the colon):

#!/bin/ksh
ed -s out3 <<-EOF
        H
        1s/^//
        ?\([0-9]*\):\([0-9]*\)?s//\2:\1/
        w plotted.p
EOF

I use ksh, but any shell that uses here-documents as specified by the POSIX Standards (including at least bash, ksh, and sh) will work.

Thanks everybody for the help! I checked out 'ed' and learned some new tools to use. I ended up attacking the problem from a different point of view (more creative but it works the way I need it to). :slight_smile: