简体   繁体   English

如何使用 find & sed 删除文件中的特定字符串

[英]How to remove specific string in a file using find & sed

All my index.php were injected with我所有的 index.php 都注入了

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

at the 1st line of it.在它的第一行。

So I want to just remove that particular line "<script type='text/javascript' src='https://www.example.com/home/public′></script>" via Terminal in Cpanel running CentOS所以我想通过运行 CentOS 的 Cpanel 中的终端删除特定的行"<script type='text/javascript' src='https://www.example.com/home/public′></script>"

I do some research and I have came up with this:我做了一些研究,我想出了这个:

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

The terminal shows an error: find: missing argument to `-exec' bash: {}+: command not found终端显示错误:find: missing argument to `-exec' bash: {}+: command not found

You've just ended your line too fast!你刚刚结束你的线路太快了! The ; ; should be at the end of the line.应该在行尾。

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

(be careful, there some quotes/anti quotes or typographic quotes in your example... it could be confusing) (请注意,您的示例中有一些引号/反引号或印刷引号......这可能会令人困惑)

But I see 2 informations in your question (first line + a pattern).但是我在您的问题中看到了 2 个信息(第一行 + 一个模式)。

The easiest way (not the only one), wouldn't be to delete the first line of all the index.php files?最简单的方法(不是唯一的),不是删除所有 index.php 文件的第一行吗?

If so, just use:如果是这样,只需使用:

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

You also can use for instead of exec :您也可以使用for而不是exec

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

On macOS/freeBSD style, just add '' in sed :在 macOS/freeBSD 风格中,只需在sed中添加''

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

If you are looking to delete an entire pattern, you will need to protect special chars and so on, and you will need to be careful not to delete, for example, the same but useful pattern at any other place in your files .如果您要删除整个模式,则需要保护特殊字符等,并且需要注意不要删除文件中任何其他位置的相同但有用的模式 So be careful.所以要小心。

I assume that's because you are using hash character # as regex delimiter.我认为这是因为您使用 hash 字符#作为正则表达式分隔符。 My personal favorite there is using at sign @ for the same, thus:我个人最喜欢的是使用 at 符号@相同的,因此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM