1

I am trying to delete range of line numbers using sed command within php using exec command. I know how to use sed when substituting values directly within command.

exec("sed -i.bak -e '2d;12,17d;57d' $filename", $outputArray);

Note: the range will be chosen by the user and hence directly using the above command will not help me; it should be a variable.

For example, I want something like this:

<?php
$delete_from_line=35;
$delete_to_line=40;
exec("sed -i.bak -e "$delete_from_line,$delete_to_line" $filename", $outputArray);
?>
1

Try this:

<?php
$delete_from_line=35;
$delete_to_line=40;
$filename="/path/to/your/file";

exec('sed -i.bak ' . $delete_from_line . ',' . $delete_to_line . 'd ' . $filename);
?>

See: http://php.net/manual/en/function.exec.php

  • Thanks @Cyrus , that worked :) , but it works only when i execute with sudo php filename.php else if i just use php filename.php it throws couldn't open temporary file , permission denied – Abhishek J Jan 7 '17 at 10:33
  • The user (apache, httpd ...) which runs your php code needs write permissions to the directory which contains the file you want to edit. – Cyrus Jan 7 '17 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.