避免 file_get_contents 一次性讀入記憶體,採用逐行讀取 + 雜湊集合去重。
<?php
/**
* 刪除文本文件重複行(記憶體高效版)
* @param string $filepath 文件路徑
* @param bool $ignoreCase 忽略大小寫
* @param string $newLine 換行符
* @return int 刪除的重複行數
*/
function removeDuplicateLines($filepath, $ignoreCase = false, $newLine = "\n") {
if (!is_file($filepath) || !is_readable($filepath)) {
throw new InvalidArgumentException("File not found or not readable: $filepath");
}
$tempFile = $filepath . '.tmp.' . uniqid();
$seen = [];
$removed = 0;
$fin = fopen($filepath, 'r');
$fout = fopen($tempFile, 'w');
if (!$fin || !$fout) {
throw new RuntimeException("Cannot open file handles");
}
while (($line = fgets($fin)) !== false) {
$line = rtrim($line, "\r\n"); // 統一去除行尾換行符
if ($line === '') continue; // 跳過空行(可選)
$key = $ignoreCase ? strtolower($line) : $line;
if (isset($seen[$key])) {
$removed++;
continue;
}
$seen[$key] = true;
fwrite($fout, $line . $newLine);
}
fclose($fin);
fclose($fout);
// 原子性替換
if (!rename($tempFile, $filepath)) {
unlink($tempFile);
throw new RuntimeException("Failed to replace original file");
}
return $removed;
}
// 使用範例
try {
$removed = removeDuplicateLines('/var/log/access.log', true);
echo "去重完成,移除 $removed 行重複內容\n";
} catch (Exception $e) {
echo "錯誤: " . $e->getMessage() . "\n";
}
?>
<?php
class FileDeduplicator {
private $stats = ['total'=>0, 'unique'=>0, 'duplicates'=>0, 'empty'=>0];
public function deduplicate(
string $inputFile,
string $outputFile = null,
array $options = []
): array {
$opts = array_merge([
'ignore_case' => false,
'skip_empty' => true,
'trim_whitespace' => true,
'encoding' => 'UTF-8',
'max_memory_mb' => 128, // 超過則分塊處理
], $options);
$outputFile = $outputFile ?? $inputFile;
$tempFile = $outputFile . '.dedup.' . uniqid();
$seen = [];
$fin = fopen($inputFile, 'r');
$fout = fopen($tempFile, 'w');
while (($line = fgets($fin)) !== false) {
$this->stats['total']++;
if ($opts['trim_whitespace']) {
$line = trim($line);
} else {
$line = rtrim($line, "\r\n");
}
if ($line === '') {
$this->stats['empty']++;
if ($opts['skip_empty']) continue;
}
$key = $opts['ignore_case'] ? mb_strtolower($line, $opts['encoding']) : $line;
if (isset($seen[$key])) {
$this->stats['duplicates']++;
continue;
}
$seen[$key] = true;
$this->stats['unique']++;
fwrite($fout, $line . "\n");
// 記憶體保護:超過限制時分塊寫入磁碟
if (memory_get_usage(true) > $opts['max_memory_mb'] * 1024 * 1024) {
$this->flushSeenToDisk($seen, $tempFile . '.index');
$seen = [];
}
}
fclose($fin);
fclose($fout);
rename($tempFile, $outputFile);
return $this->stats;
}
private function flushSeenToDisk(array &$seen, string $indexFile) {
// 實際專案可用 SQLite、LevelDB 或分塊文件存儲 seen 集合
// 此處簡化示意
}
}
// 使用
$dedup = new FileDeduplicator();
$stats = $dedup->deduplicate('keywords.txt', 'keywords_unique.txt', [
'ignore_case' => true,
'skip_empty' => true
]);
print_r($stats);
// 針對 CSV、自定義分隔符
function deduplicateByDelimiter($filepath, $delimiter = ',', $columnIndex = 0) {
$seen = [];
$fin = fopen($filepath, 'r');
$fout = fopen($filepath . '.dedup', 'w');
while (($row = fgetcsv($fin, 0, $delimiter)) !== false) {
$key = $row[$columnIndex] ?? '';
if ($key === '') continue;
if (isset($seen[$key])) continue;
$seen[$key] = true;
fputcsv($fout, $row, $delimiter);
}
fclose($fin);
fclose($fout);
rename($filepath . '.dedup', $filepath);
}
| 方法 | 記憶體 | 耗時 | 適用規模 |
|---|---|---|---|
| file() + array_unique() | 高(全載入) | 快 | < 10 萬行 |
| fgets() 逐行 + 陣列去重 | 中(僅存鍵) | 中 | 10 萬 - 500 萬行 |
| 流式 + 外部排序/資料庫 | 低(常數) | 較慢 | > 500 萬行 |
Linux sort -u | 系統管理 | 最快 | 超大文件、批次處理 |
# 簡單去重(保留首次出現順序)
awk '!seen[$0]++' input.txt > output.txt
# 忽略大小寫去重
awk '!seen[tolower($0)]++' input.txt > output.txt
# 指定欄位去重(第 1 欄)
awk -F',' '!seen[$1]++' input.csv > output.csv
# 排序後去重(改變順序)
sort -u input.txt > output.txt
PHP 處理文本去重關鍵在於流式讀取避免記憶體溢出,配合雜湊集合 O(1) 查重。小文件用內建函數簡潔,大文件需分塊處理或呼叫系統命令。生產環境建議:預處理用 sort -u,業務邏輯用 PHP 流式去重並記錄統計資訊。