我有许多以数字命名的日志文件。
100001.txt
100002.txt
...
119998.txt
119999.txt
现在我想将它们与每 10 个数字组合在一起。 例如:100000.txt - 100009.txt
->命名为 10000a.txt
, 100010.txt - 100019.txt -> named
10001a.txt , 100020.txt - 100029.txt
-> 命名为 10002a.txt
...119990.txt - 119999.txt -> named
11999a.txt'。然后删除了所有旧文件。
$files = glob('/var/logs/my_log/'*');
foreach($files as $file){
$num = str_replace(array('/var/logs/my_log/','.txt'),'',$file);//get numbers like 100000
if($num%10==0){
$name = substr($num, 0, -1).'a.txt';//10001a.txt
foreach(array_chunk($num, 10) as $values) {
echo $values.'<br>';//this will group by 1000001-1000010, but i need 1000000-1000009
//chmod('/var/logs/my_log/'.$values.'.txt',0777);//should i set 0777 for write and remove files?
//$txt.=file_get_contents('/var/logs/my_log/'.$values.'.txt');//get old files value
//unlink('/var/logs/my_log/'.$values.'.txt');//remove old files
}
//file_fut_contents('/var/logs/my_log/'.$name.'.txt',$txt);//save into new file
//$name=$txt=NULL;//unset var
}
}
您可以使用
fopen($filename, $mode)
函数来实现此目的。它具有追加模式,可将文件指针放置在给定文件的末尾。从那里您可以使用其他文件功能,例如 fwrite()
和 fclose()
.手册中有一些关于如何使用 fopen 的很好的例子
自己找出方法。
<?php
$files = glob('/var/logs/my_log/*');
foreach($files as $file){
$num =str_replace(array('.txt','/var/logs/my_log/'),'',$file);
$txt.=file_get_contents($file).'/r/n';
if(substr($num,-1)==9){
file_put_contents('/var/logs/my_log/'.substr($num,0,-1).'a.txt',$txt);
$txt=NULL;
}
unlink($file);
}
?>