1

How can I find a string in a file, then find the first instance of a tag that precedes it and then delete everything between that tag and it's closing tag, and then repeat the process ad nauseam throughout the rest of the file?

I've been looking at sed for this but as far as I can see you would have to specify a number of lines to delete and the amount of lines between the two tags can vary.

  • 5
    It would be helpful if you provide a short example in your question. – jofel Dec 4 '14 at 11:30
1

Assuming tags don't nest:

perl -0777 -pe 's{<tag>.*?</tag>}{
  my $r = $&; $r =~ /string/ ? "" : $r}gse' < "$file"
  • Thanks Stephane. I've never used perl before - where do I specify what file I'm using? Do I just tack it on at the end? – Alistair67 Dec 4 '14 at 13:23
  • Wonderful Stephane, thank you so much. Once I had added an output file at the end this gave me exactly what I wanted. Most grateful. – Alistair67 Dec 4 '14 at 13:47
0

You can do this w/ sed. The idea is to stack the lines between the tags every time. When a stack contains string, delete it, else print it.

sed ':n
/<tag1>.*string.*<tag2>/d;$q;N
/<tag1>.*<tag2>/!bn'

If the file is very large - or, more precisely, if there is a very large amount of file between tags 1 and 2 or vice versa - this command could get cumbersome or even intractable. With some more code it can be optimized to handle those situations - and a GNU sed should present you no difficulties in most situations this way anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.