开发者

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

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 o开发者_如何学Cf 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.


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.


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
    }
}


With grep:

grep -v '#3$' filename

With sed:

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

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


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');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜