本文将使用 php 和 linux sort 命令两种方法,分别实现文件内容去重及排序,并提供完成演示代码。
1.创建测试文件
写入1000000个数字,每行一个数字
<?php
$file = 'user_id.txt';
$num = 1000000;
$tmp = '';
for($i=0; $i<$num; $i++){
$tmp .= mt_rand(0,999999).PHP_EOL;
if($i>0 && $i%1000==0 || $i==$num-1){
file_put_contents($file, $tmp, FILE_APPEND);
$tmp = '';
}
}
?>
查看文件行数
wc -l user_id.txt
1000000 user_id.txt
2.php实现去重及排序
因要处理1000000行数据,因此将php可使用的内存设置为256m,防止执行过程中内存不足。
<?php
/**
* 文件内容去重及排序
* @param String $source 源文件
* @param String $dest 目标文件
* @param String $order 排序顺序
* @param Int $sort_flag 排序类型
*/
function fileUniSort($source, $dest, $order='asc', $sort_flag=SORT_NUMERIC){
// 读取文件内容
$file_data = file_get_contents($source);
// 文件内容按行分割为数组
$file_data_arr = explode(PHP_EOL, $file_data);
// 去除空行数据
$file_data_arr = array_filter($file_data_arr, 'filter');
// 去重
$file_data_arr = array_flip($file_data_arr);
$file_data_arr = array_flip($file_data_arr);
// 排序
if($order=='asc'){
sort($file_data_arr, $sort_flag);
}else{
rsort($file_data_arr, $sort_flag);
}
// 数组合拼为文件内容
$file_data = implode(PHP_EOL, $file_data_arr).PHP_EOL;
// 写入文件
file_put_contents($dest, $file_data, true);
}
// 过滤空行
function filter($data){
if(!$data && $data!=='0'){
return false;
}
return true;
}
// 设置可使用内存为256m
ini_set('memory_limit', '256m');
$source = 'user_id.txt';
$dest = 'php_sort_user_id.txt';
fileUniSort($source, $dest);
?>
查看去重及排序后的文件
wc -l php_sort_user_id.txt
632042 php_sort_user_id.txt
head php_sort_user_id.txt
0
1
2
3
5
7
8
9
11
12
...
3.linux sort命令实现去重及排序
linux sort命令用于文本文件按行排序
格式:
sort [OPTION]... [FILE]...
参数说明:
-u 去重
-n 数字排序类型
-r 降序
-o 输出文件的路径
使用sort执行去重及排序
sort -uno linux_sort_user_id.txt user_id.txt
查看去重及排序后的文件
wc -l linux_sort_user_id.txt
632042 linux_sort_user_id.txt
head linux_sort_user_id.txt
0
1
2
3
5
7
8
9
11
12
...
总结:使用php或linux sort命令都可以实现文件去重及排序,执行时间上相差不大,但建议对于文件类的操作,直接使用系统命令实现更为简单。