linux命令:文件的合并、去重、拆分、删除一列、删除多列

1.文件的合并

# 合并1,2到3:
cat 1 2 >> 3
# 追加1到2
cat 1 >> 2
# train.txt文件中拿出7500行到train_7500.txt
head -7500 train.txt > train_7500.txt

2.一个文件去掉重复的行

$ sort file |uniq > file_1   # 重复的多行记为一行
eg:
file中的内容如下:
1
2
3
4
1
2
3
调用上述命令后的输出file_1结果:
1
2
3
4

$ sort file |uniq -u  > file_2   # 重复的行全部去掉
输出的结果:
4

3.两个文件的交集、并集(前提条件:每个文件中不得有重复行)

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

  cat file1 file2 | sort | uniq > file3

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

  cat file1 file2 | sort | uniq -d > file3

3. 删除交集,留下其他的行

  cat file1 file2 | sort | uniq -u > file3

4.删除文件的一列

原始文件 xxx.txt 内容如下:
1   1
2   1
3   1
4   1

想要把txt中的第二列的内容删除,可使用如下命令:
cat xxx.txt | awk -F, '{$2=null;print $0}' | awk 'BEGIN{OFS=",";}{print $1}' > afterxxx.txt

afterxxx.txt文件的结果:
1
2
3
4

如果要删除很多列,那么枚举的方式则比较麻烦,这里使用for循环:
awk '{for(i=4;i<NF;i++)printf("%s ",$i);print $NF}' filename >newfilename

おすすめ

転載: blog.csdn.net/pearl8899/article/details/120007034
おすすめ