如何判断文件是否有重复的行? Windows程序员估计要歇菜了, 还是省省吧, linux搞起:
taoge@localhost test> cat a.txt
xxx
111
xxx
taoge@localhost test> wc -l a.txt
3 a.txt
taoge@localhost test>
taoge@localhost test>
taoge@localhost test>
taoge@localhost test> sort a.txt | uniq > b.txt
taoge@localhost test> wc -l b.txt
2 b.txt
taoge@localhost test>
文件由3行变成了2行, 所以a.txt中有重复的行。
再看:
taoge@localhost test> cat c.txt
xxx
111
xxx111
taoge@localhost test> wc -l c.txt
3 c.txt
taoge@localhost test>
taoge@localhost test>
taoge@localhost test>
taoge@localhost test> sort c.txt | uniq > d.txt
taoge@localhost test> wc -l d.txt
3 d.txt
taoge@localhost test>
行数没有变化, 可见c.txt中没有重复的行。
当然, 还有更简单的方法,如下:
taoge@localhost test> sort a.txt | uniq -d
xxx
taoge@localhost test> sort c.txt | uniq -d
taoge@localhost test>
其中, uniq -d是输出duplicate了的行, 也就是重复的行。 要注意, 这是建立在sort后的基础之上的。
在实际开发中, 要经常处理类似问题, 那些还在想怎么去写程序来判断的朋友, 可以换个角度考虑一下了。