简体   繁体   中英

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

All my index.php were injected with

<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

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

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).

The easiest way (not the only one), wouldn't be to delete the first line of all the index.php files?

If so, just use:

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

You also can use for instead of exec :

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

On macOS/freeBSD style, just add '' in 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. My personal favorite there is using at sign @ for the same, thus:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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