Recently my server has been a target for a series php exploit attacks and using ClamAV I was able to identify many infected files.The catch here is that there are legitimate files that are infected along with some that are utterly malicious code.  Fortunately the infected files are in the following format:<?php //malicious code ?><?php //legitimate part ?>So I though I could use sed to remove only the first occurrence of the php tag. This way the legitimate code stays intact and malicious part gets deleted.For that I have used the following command:sed 's/<?php.*?>//' file.phpThis has 2 problems:It replaces every single occurrence instead of the firstIt fails for multi-line occurrencesI have used many forms but they have all failed at a point.sed '0,/<?php.*?>/{s/<?php.*?>//}' //this has also failedSo I thought maybe you guys can give me a hint on how to make this sed command work or suggest any better tool for the task at hand.
Cleaning PHP exploits from infected files using sed
sed;regular expression;string
Sorry that I use perl oneliner expresion instead sed, but somehow I cant learn/remember sed's regex. So you can try this:  $ cat somefile.php | tr '\n' '@@@' | perl -p -e 's/^(.*?)(<\?php.*?\?>)(.*$)/$1$3/' | tr '@@@' '\n' > somefile_1.phpFirst tr is for changing multiline string in oneline string. The '@@@' string is just an example, it can be any string that does not exist in any files you want to edit (grep it first just to be sure).Next the perl command is doing the actual work: using regex groups it is spliting string on three parts - first everything before first occurence of php block, next php block itself and last everything after first php block. Please notice that ? character is used to make wildcard expression .* non greedy, and the other question marks has to be escaped.The last tr brings newlines back (it has to use the same string which was used in first tr - in this example '@@@').