I have a file in which i want replace last occurrence of string in third to the last line in a file. I have a file like:

  analyze_compression_testpoints -log no -TESTMODE FULLSCAN
  -EXPERIMENT <br /> azul_rrfa -outputfile
  ./testresults/testinsertion.file<br />

I want to replace <br /> with </font> in the third last line only. I am using:

sed -i "s|\(.*\)<br />\$|\1</font>|g"

but it is replacing all the last occurrence in each line, but i want only last occurrence of file, not each line.

2 Answers 2


With sed:

tac file | sed '3 s|<br />$|</font>|' | tac

With ed:

echo -e '$-2s/<br \/>$/<\/font>/\nw' | ed -s file

With vim:

:$-2 s!<br />$!</font>!
  • Thanks for reply, but how to insert in a file, as sed -i is not working in this case. I want to insert/replace directly from command.
    – Rash
    Commented Sep 5, 2017 at 17:48
  • 1
    @Rash Use the ed solution. Commented Sep 5, 2017 at 17:59
  • ed is also not working here. giving output as question mark (?). Please suggest.
    – Rash
    Commented Sep 6, 2017 at 4:55
  • @Rash I suggest you try the ed solution exactly the way I wrote it. Commented Sep 6, 2017 at 5:12
  • Yes, I have tried exactly the same command but not working, I am running it on shell prompt.
    – Rash
    Commented Sep 6, 2017 at 5:55

As this is the last occurrence in the file, you can use this sed script:

sed -i 'H;1h;$!d;g;s_\(.*\)<br />_\1</font>_' yourfile.html

or simplified with GNU sed and extended regular expression:

sed -izE 's_(.*)<br />_\1</font>_' yourfile.html

The trick is to process the whole file in one buffer. The POSIX version does this by collecting in the hold buffer, the GNU version uses option -z for this. Then, with s command replace everything (.*) including the last occurrence of the pattern by everything before the pattern (the \1 refers to the part in ()) and the replacement.

Other attempt, if you really require to replace only on the third to last line (no replacement if there is no match, no replacing on the next-to-last or last line):

sed '1N;N;$!{P;D];s_<br />_</font>_' yourfile.html

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .