Reputation: 11394
I have the following code in a larger file
}
catch (PDOException $e){
echo 'Error: '. $e->getMessage();
}
I am trying to delete these four lines out of the file using sed but cannot seem to figure it out. Each line may have preceding or trailing white space.
The following which I thought should work does not work:
sed '1N;$!N;s/.*}.*\n.*catch.*\n.*Error.*\n.*}.*//;P;D' myfile.php
The weird thing is that
sed '1N;$!N;s/.*}.*\n.*catch.*\n.*Error.*//;P;D' myfile.php
deletes the first three lines. And
sed '1N;$!N;s/.*catch.*\n.*Error.*\n.*}.*//;P;D' myfile.php
deletes the last three lines.
Why doesn't it work for all four lines?
I also don't completely understand why I need the $!N for this to work, so if you can explain what exactly that is doing that will help my understanding as well.
Thanks!
Upvotes: 0
Views: 126
Reputation: 58438
This might work for you (GNU sed):
sed ':a;N;s/\n/&/3;Ta;/^\s*}\n.*catch.*\n.*Error.*\n\s*}$/d;P;D' file
This solution make a moving window of four lines in the pattern space (PS) and if the desired pattern matches the PS those four lines are deleted. Otherwise the first of the lines is printed and then deleted and another line appended to the PS and the match tried again until a match or the end of the file is reached.
N.B. sed by design removes any newlines before populating the PS. the N
command appends a newline followed by the next line to the PS.If the N
command is called following the end of the file, no further commands are executed and the PS is printed (unless the -n
option is in operation).
Upvotes: 1
Reputation: 158060
As I said here, you'll get a syntax error in PHP if you remove the catch block.
Btw, you can use php
for that task. PHP supports recursive regex patterns which can be used here:
<?php
$string = <<<'EOF'
}
catch (PDOException $e){
echo 'Error: '. $e->getMessage();
}
EOF;
// Check http://php.net/manual/de/regexp.reference.recursive.php
$pattern = '/catch .*\{(((?>[^{}]+)|(?R))*)\}/';
echo preg_replace($pattern, '', $string);
sed
does not pattern recursion in that way.
Upvotes: 0