how to delete a line(record) from a file using php

360 Views Asked by At

I want to delete a line which has unique id at the end of the line. how to delete the line? Is there any implementation of sed or awk in php? my file structure is as follows

1 0 * * *  echo -n "cron 1" > /www/apache/logs/error_log #1
0 */2 * * *  /home/user/test1.pl #2
1 0 * * *  echo -n "cron 2" > /www/apache/logs/error_log #3
0 */2 * * *  /home/user/test2.pl #4
1 0 * * *  echo -n "cron 3" > /www/apache/logs/error_log #5
0 */2 * * *  /home/user/test3.pl #6

in the above example unique id is at the end of each line with "#" followed by the integer id value. How to delete a line by identifying with its unique key? Thanks.

4

There are 4 best solutions below

0
kurumi On BEST ANSWER

with awk, (eg deleting #4 line )

awk -v uniq="#4" '$NF!~uniq' file > temp && mv temp file

in PHP, you can iterate the file and look for the id with regex : "#\d+$", or you can split the line on whitespace and check that the last element is not the uniq number you specified.

0
seriyPS On

Smth like

foreach($lines as $line){
    if(preg_match("/#(\d+)/$"), $line, $matches) && ($matches[1]==$drop_line_num)){
        #DON'T write line in output file
    }else{
        #write line to output file
    }
}
0
mohit6up On

With grep:

grep -v '#3$' filename

With sed:

sed -e '/#3$/d' filename

to remove only the line with a #3 at its end.

0
akond On

Bare PHP will do.

function removeTaggedLine ($tag, $file_name)
{
    $lines = preg_grep ("/#$tag$/", file ($file_name, FILE_IGNORE_NEW_LINES), PREG_GREP_INVERT);
    file_put_contents ($file_name, join ("\n", $lines) . "\n");
}

removeTaggedLine ('3', 'name of the file');