Linux下文本文件合并和去除重复操作。

转自品略网:http://www.pinlue.com/article/2020/03/0911/0910001580919.html

 

Linux下处理文本的能力还是很强大的。

本文主要涉及到的命令为cat  uniq sort。

一 命令简单介绍

cat:将文本文件读出来 (concatenate files and print on the standard output)

文件去重合并的前提条件是先取出文件的内容。

uniq: 用来处理重复的行。(report or omit repeated lines)

Filter  adjacent matching lines from INPUT (or standard input), writing to OUTPUT (or  standard output).

从输入或者标准输入中过滤邻近的行,写到输出文件或者标准输出中。所以此命令只能处理邻近的行,

如果对两个文件进行合并去重,则必须首先对其排序,实现一一对应,否则去重失败。

sort:对文本的行进行排序(sort lines of text files)

Write sorted concatenation of all FILE(s) to standard output.

对于去重而言使用默认排序方式就可以了。

paste:merge lines of files

将按行将不同文件行信息放在一行。缺省情况下, p a s t e连接时,用空格或t a b键分隔新行中不同文本,除非指定- d选项,它将成为域分隔符。

二 实例应用:

1、 两个文件的交集、并集(前提条件:每个文件中不得有重复 也可以是多个文件)

(1)、取出两个文件的并集(重复的行只保留一份)

[python]

cat file1 file2 | sort | uniq > file3

(2)、取出两个文件的交集(只留下同时存在于两个文件中的文件)

[python]

cat file1 file2 | sort | uniq -d > file3

(3)、 删除交集,留下其他的行

[python]

cat file1 file2 | sort | uniq -u > file3

2、两个文件合并

(1)、 一个文件在上,一个文件在下

[python]

cat file1 file2 > file3

(2)、 一个文件在左,一个文件在右

[python]

paste file1 file2 > file3

3、一个文件去掉重复的行

(1)、 重复的多行记为一行

[python]

sort file |uniq

(2)、 重复的行全部去掉

[python]

sort file |uniq -u

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值