Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed: append after last occurrence

Tags:

sed

Let's say I have the following kind of file:

<?xml version="1.0" encoding="utf-8"?>
<preferences>
  <section id="widgets">
    <value id="version" xml:space="preserve">1</value>
  </section>
  <section id="wuid-b2a8e6b8-6619-714e-9cfe-466c27c90902">
    <value id="path to widget data" xml:space="preserve">{Preferences}widgets/opera-adblock-1.3.4-1.oex</value>
  </section>
  <section id="wuid-0c5cfdb2-8e51-f149-a1e7-51d66240ed7a">
    <value id="path to widget data" xml:space="preserve">{Preferences}widgets/flag-button-1.5.4-1.oex</value>
  </section>
</preferences>

My mission is to add text right after the last occurrence of </section>.

Looking at these two it seems as if utilizing tac would be simpler but I don't understand how to do that either: Using sed to append a string to the fourth occurrence of a pattern, http://www.unix.com/unix-dummies-questions-answers/46294-add-line-after-last-occurnace-pattern.html#post302149709

Thanks.

like image 930
Det Avatar asked Dec 12 '22 18:12

Det


1 Answers

This might work for you (GNU sed):

sed '/\/section/{x;/./p;x;h;d};x;/./!{x;b};x;H;$!d;x;s/\/section[^\n]*\n/&  HELLO\n/' file

In essence: on encountering a line containing /section start storing all remaining lines to the end of the file in the hold space (HS). If lines are already in the hold space and another such line is encountered print the lines in the HS and begin storing lines again. At the end of the file insert the desired string and print out the stored lines.

like image 120
potong Avatar answered Feb 03 '23 20:02

potong