0

I am looking to remove everything before multiple HTML matching lines across all the files in current folder using Perl or sed command.

This is what one of my files in the current folder looks like:

<li>violet</li>
<p>red</p>
<p>blue</p>
<p>gray</p>

<li><a href="#part1">Part 1</a>

</li>
<h2>Part 1</h2>
<p>pink</p>

I am trying to remove everything before matching these HTML lines (which can contain empty lines as you can see):

<li><a href="#part1">Part 1</a>

</li>

So the final edited file would look like this:

<h2>Part 1</h2>
<p>pink</p>

I found that Perl can remove everything before specific characters using:

perl -p -e 's/^.*?abc/abc/'

and sed:

sed 's/[^abc]*\(abc.*\)/\1/'

but I wasn't able to match these to html tags.

If anyone has any suggestions, that would be awesome!

3
  • 1
    I would strongly recommend looking at using a tool like xmlint to parse out your file. Bash/awk/sed/perl are not suited to handle the permutations available in xml/html. Once you're able to reliably parse the input you might be able to match the needed output.
    – doneal24
    May 25, 2022 at 19:55
  • thanks a lot! will look into it, thanks!
    – Lernisios
    May 25, 2022 at 20:07
  • 1
    @doneal24 Perl can parse html/xml just fine. I just wouldn't use a regex to do it. There are plenty of libraries that will get the job done. May 25, 2022 at 20:44

1 Answer 1

1

I wouldn't parse HTML with a regex, but simply based off "print things after and including <h2>" you can do this,

perl -nE'state $start ||= m?<h2>? and print' ./test

Even in Perl you wouldn't use a regex. You would use something Mojo::DOM to do what you want, and not a regex.

2
  • would this match the first <h2> found in the code? that would work for me, it's not ideal, but it's usually the first <h2> in all the files. Thus, if my filenames are "test1.txt", "test2.txt" etc, in your Perl command, how can i overwrite them and print directly in the existent files? (basically to print things inside them directly) Thank you!
    – Lernisios
    May 25, 2022 at 20:48
  • it matches my first <h2> found in the code, works good so far. would it be a way for me to run the Perl command and apply it directly to the files? (overwrite them with the changed text)
    – Lernisios
    May 25, 2022 at 20:55

You must log in to answer this question.

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