RandomWhiteTrash
RandomWhiteTrash

Reputation: 4014

Replacing multiple lines in awk (or something)

I have been trying to accomplish the following with SED but since SED is line based I am afraid I won't be able to do it:

sed -ri 's/(<li>\n\s+<a href="#introduction")/<li><div class="toc-group">Topics<\/div><\/li>\1/' index.php

This is supposed t change this:

          <li>
        <a href="#introduction" class="toc-h1 toc-link" data-title="Introduction">Introduction</a>

into this

<li><div class="toc-group">Topics<\/div></li><li>
        <a href="#introduction" class="toc-h1 toc-link" data-title="Introduction">Introduction</a>

Basically a poor man's 'add a line in a specific place'. Unfortunately \n does not work as expected. I think AWK can do this but SED is the only tool I ever used and I know nothing about AWK so can please help me with a solution.

FYI There is more than one item that needs to be added in different parts of the document so I need a solution that will allow me to choose a part of a code and then prepend in front of it. It will be utilised in a bash script for automation.

Upvotes: 1

Views: 1018

Answers (2)

srsr98
srsr98

Reputation: 11

I've just started to learn sed and awk but this syntax appears to add line between text.

 sed 's/<li>/<li><div class="toc-group">\n/g' x.txt

Output:

<li><div class="toc-group">
<a href="#introduction" class="toc-h1 toc-link" data-
title="Introduction">Introduction</a>

I've only put a subset of your index.php to reduce length of the example. The output here shows a split of the a href=... line but it's one line when I run the script, so it's just an editing issue in this post.

Upvotes: 0

Toto
Toto

Reputation: 91518

How about a perl one-liner:

perl -0777 -ne 's/(<li>\n\s+<a href="#introduction")/<li><div class="toc-group">Topics<\/div><\/li>$1/; print' inputfile

Output:

      <li><div class="toc-group">Topics</div></li><li>
    <a href="#introduction" class="toc-h1 toc-link" data-title="Introduction">Introduction</a>

Upvotes: 1

Related Questions