删除文本文件中的重复行 [英] Remove duplicate lines in a text file

查看:118
本文介绍了删除文本文件中的重复行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要打开一个文本文件(file.txt),其中包含以下格式的数据:-

I am in need to open a text file (file.txt) which contains data in the following format :-

dave : 50lb : hlof
jimmy : 55lb : okay
dave : 12lb : krsho

我想删除起始单词重复的行,所以结果看起来像这样:-

I want to remove lines that has duplicate start word So the result would look like this :-

dave : 50lb : hlof
jimmy : 55lb : okay

我一直在考虑使用array_unique,但是没有用,所以任何想法都可以做到的..也许可以使用regex

I've been thinking about using array_unique but didn't worked so any idea how it can be done .. maybe can be with regex !

更新

我的尝试是

$lines = file('file.txt');
$lines = array_unique($lines);
file_put_contents('file.txt', implode($lines));

但是没有用,因为它只比较整行,如果不一样则会认为它不同

but didn't worked cause it only compare the whole line if not the same will then consider it different

推荐答案

这应该对您有用:

(在这里,我首先使用 array_map() 然后我 explode() 每个带有:的值并返回第一个元素.之后,我将 array_intersect_key() 与从我使用 array_unique() 来获取唯一键之前创建的数组并得到完整数组的相交)

(Here I first go through each element of $lines with array_map() then I explode() every value with : and return the first element. After this I use array_intersect_key() with the created array from before where I use array_unique() to get the unique keys and get the intersect with the full array)

<?php

    $lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    $lines = array_intersect_key($lines, array_unique(array_map(function($v){
        return trim(explode(":", $v)[0]);
    }, $lines)));

    print_r($lines);

?>

输出:

Array ( [0] => dave : 50lb : hlof [1] => jimmy : 55lb : okay )

这篇关于删除文本文件中的重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆