1

So I already went through a couple of the similiar questions but I couldn't get anything to work.

I am currently trying to use this:

sed -i '/^<script/,/script>/{/^<script/!{/script>/!d}}' file.txt

Which I thought would delete everything between <script and script> but as you might have guessed it doesn't do so.

this is the code that is in the txt file:

<script type="text/javascript">
 bla bla some script bla bla
</script>

There are multiple scripts at various places in the .txt and it is supposed to delete every single one of them.

  • What is the significance of the gitlab tag on this question? Are you processing XML documents? What do the documents look like? Do you just wish to delete the script nodes and their contents unconditionally? – Kusalananda Aug 12 at 9:45
  • Please add sample input (no descriptions, no images, no links) and your desired output for that sample input to your question (no comment). – Cyrus Aug 12 at 9:52
  • @Kusalananda I am using sed in the gitlabci.yml. – SirHawrk Aug 12 at 9:56
  • So it's not an XML file? – Kusalananda Aug 12 at 10:03
  • 1
    (1) During testing, you should always drop the -i option. You can debug more easily and avoid messing up your file. (2) Your script looks good and removes the bla line in your example here, which is what you want, I suppose. What is your sed version? – Philippos Aug 12 at 10:14
1

If you want to delete the text between opening and closing script tags where the opening one is always at the start of a line, all you need is:

sed -i '/^<script/,/<\/script>/d' file

Of course, using sed for things like this is a bad idea and you should use a proper parser instead. For instance, what if your input file contains nested blocks?

<script type="text/javascript">
 bla bla some script bla bla
<script>
    foo
</script>
</script>

But whether or not that is an issue will depend on your input data.

  • That Stackoverflow post was really interesting thank you very much. How would I do that if the script wasn´t at the beginning of the line? E.g. seperated by whitespace? Also what would you use instead of sed? – SirHawrk Aug 12 at 10:55
  • @SirHawrk it depends on the input file. If you're parsing a structured language like XML or HTML, use a dedicated parser for it. Other people have already done the work for you, and almost certainly better than you or I would do it, so don't reinvent the wheel. For the simple case you show, if it can have whitespace before it (but nothing else), you could try sed -i '/^[[:space:]]*<script/,/<\/script>/d' file. – terdon Aug 12 at 11:11
  • @SirHawrk to give you an idea, this is the sort of level of regex expertise you need to write your own parser. – terdon Aug 12 at 11:13

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.