如何使用php从文件中删除行(记录)
我想删除在行尾具有唯一id的行。如何删除该行?在php中是否有sed或awk的实现?我的文件结构如下 10***echo-n“cron 1”>/www/apache/logs/error#u log#1 0*/2***/home/user/test1.pl#2 10***echo-n“cron 2”>/www/apache/logs/error#u log#3 0*/2***/home/user/test2.pl#4 10***echo-n“cron 3”>/www/apache/logs/error#u log#5 0*/2***/home/user/test3.pl#6 在上面的示例中,唯一id位于每行末尾,后跟“#”和整数id值。如何通过标识行的唯一键来删除行?谢谢。使用awk(例如删除#4行) 在PHP中,您可以迭代文件并使用正则表达式查找id:如何使用php从文件中删除行(记录),php,file,sed,awk,file-processing,Php,File,Sed,Awk,File Processing,我想删除在行尾具有唯一id的行。如何删除该行?在php中是否有sed或awk的实现?我的文件结构如下 10***echo-n“cron 1”>/www/apache/logs/error#u log#1 0*/2***/home/user/test1.pl#2 10***echo-n“cron 2”>/www/apache/logs/error#u log#3 0*/2***/home/user/test2.pl#4 10***echo-n“cron 3”>/www/apache/logs/er
“#\d+$”
,或者您可以在空白处拆分行,并检查最后一个元素是否不是您指定的uniq编号。使用awk(例如删除#4行)
在PHP中,您可以迭代文件并使用正则表达式查找id:“\d+$”
,也可以在空白处拆分行,并检查最后一个元素是否不是您指定的uniq编号。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
}
}
类Smth
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
}
}
使用
grep
:
grep-v'#3$”文件名
使用sed
:
sed-e'/#3$/d'文件名
要仅删除末尾带有
#3
的行。带有grep
:
grep-v'#3$”文件名
使用sed
:
sed-e'/#3$/d'文件名
仅删除末尾带有#3
的行。裸PHP即可
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');
裸PHP就可以了
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');
惊喜php可以使用
system()
function运行外部程序,用sed标记您的问题,&awk已经是跨平台惊喜的一大缺点!php可以使用system()
function运行外部程序,用sed标记您的问题,&awk已经是跨平台的一大缺点