【问题标题】:How to remove specific string in a file using find & sed如何使用 find 和 sed 删除文件中的特定字符串
【发布时间】:2020-04-18 02:26:13
【问题描述】:

我所有的 index.php 都被注入了

<script type='text/javascript' src=’https://www.example.com/home?v=2.2.0′></script> 

在它的第一行。

所以我想通过运行 CentOS 的 Cpanel 中的终端删除该特定行 "&lt;script type=’text/javascript’ src=’https://www.example.com/home/public′&gt;&lt;/script&gt;"

我做了一些研究,我想出了这个:

find . -name “index.php” -exec sed -i “s#<script type=’text/javascript’ src=’https://www.example.com/home?v=2.2.0′></script>##g"; {} +

终端显示错误: 查找:缺少“-exec”的参数 bash:{}+:找不到命令

【问题讨论】:

  • 首先,更正你的引号。有些是非ASCII(例如“)。

标签: linux shell centos find cpanel


【解决方案1】:

你刚刚结束你的线路太快了! ; 应该在行尾。

find . -name index.php -exec sed -i "s#<script type='text/javascript' src='https://www.example.com/home'></script>##g" {} +;

(请注意,您的示例中有一些引号/反引号或印刷引号...可能会造成混淆)

但我在您的问题中看到 2 个信息(第一行 + 一个模式)。

最简单的方法(不是唯一的),是不是删除所有index.php文件的第一行

如果是这样,只需使用:

find . -name index.php -exec sed -i '1d' {} +;

您也可以使用for 代替exec

for i in `find . -name index.php`; do sed -i '1d' $i; done;

在 macOS/freeBSD 样式中,只需在 sed 中添加 ''

for i in `find . -name index.php`; do sed -i '' '1d' $i; done;

如果您要删除整个模式,则需要保护特殊字符等,并且您需要注意不要删除,例如,在任何其他地方相同但有用的模式在您的文件中。所以要小心。

【讨论】:

  • 是的,这很棒。但是,我的第一行确实涉及 标签之后的“
【解决方案2】:

我认为这是因为您使用哈希字符 # 作为正则表达式分隔符。 我个人最喜欢使用@ 来表示相同的符号,因此:

find . -name 'index.php' -exec sed -i "s@<script.*example.com.*</script>@@" {} \;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    相关资源
    最近更新 更多