当前位置:网站首页>Shell 实现文件基本操作(切割、排序、去重)
Shell 实现文件基本操作(切割、排序、去重)
2022-07-02 23:31:00 【梦幻通灵】
使用Shell 自带的工具,实现对大文本文件的操作,满足日常数据处理的需求。
一、命令 cut -切割
cut 可实现对文本按列进行文本处理,特别适合于大文件的数据处理。
基本语法是 cut [option] filename
参数
cut -f 列号,获取第几列;
cut -c 以字符为单位分割;
cut -d 以字节为单位分割,自动忽略多字节字符边界,如加 -n ,则不分割多字节字符;
cut n- 指定第n列开始;
cut n-m 指定从n列到m列;
demo演示
1)字节切割
原始文件如下所示。
获取前两列。输入命令 cut info.text -d " " -f 1-2,自定义分割,按空格分割。
2)切割bash的PID
在虚拟机中找到bash的信息,如下图所示。
执行命令 ps -aux | grep bash | head -n 1 | cut -d " " -f 8,查找bash进程,取第一行,空格分割,按列截取,取第8列,结果如下图所示。
二、命令 sort -排序
sort 对文件进行排序,并将排序结果标准或重定向输出到指定文件。
基本语法是 **sort [option] **
参数
sort -n 按照数值大小排序;
sort -r 以相反的顺序排序;
sort -t 分隔符 默认空格分隔符,排序时的分隔符;
sort -k 指定需要排序的列;
sort -o 将排序后的结果存入指定的文件;
sort -u 结果唯一,即去重过的;
demo演示
1)排序
原始文件如下所示。
执行命令 sort -t " " -k2n,2 infodata.txt,第二列按照数字升序排序,注意排序要指定从哪列到哪列,效果如下图所示。
上图结果中存在重复的数据,如何去重呢?
在命令中添加 -uk1,2,完整命令 sort -t " " -k2n,2 -uk1,2 infodata.txt,效果如下所示。
如何将重复的数据打印出来呢?
使用命令 sort infodata.txt | uniq -dc,效果如下图所示。
三、命令 uniq - 去重
uniq 以行为单位,行与行之间比较去重,只能是对有序的文本进行有效的去重,因此与sort命令结合使用。
基本语法是 **uniq [option] **
参数
uniq -c 统计行出现的次数;
uniq -d 只显示重复行并去重;
uniq -u 只显示唯一行;
uniq -i 忽略大小写;
uniq -f 忽略前N个字段,字段用空白字符分割;
demo演示
1)排序去重
只展示出现一次的行,执行命令 sort infodata.txt | uniq -u,效果如下图所示。
对于有行号的文本文件处理,使用 -f 参数忽略第一个行号字段,对之后的字段去重处理。
测试发现 sort 去重 似乎对最后一行不生效(最后一行重复未包含),在实际应用中再验证。
参考博客
【1】https://blog.csdn.net/qq_43382735/article/details/121007185
边栏推荐
- 大学生课堂作业2000~3000字的小论文,标准格式是什么?
- NC24325 [USACO 2012 Mar S]Flowerpot
- 多进程编程(三):消息队列
- Seckill system design
- Question e: merged fruit -noip2004tgt2
- What are the recommended thesis translation software?
- 布隆过滤器
- Program analysis and Optimization - 9 appendix XLA buffer assignment
- NC17059 队列Q
- Introduction of UART, RS232, RS485, I2C and SPI
猜你喜欢
详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图
Feature Engineering: summary of common feature transformation methods
论文的英文文献在哪找(除了知网)?
[target detection] r-cnn, fast r-cnn, fast r-cnn learning
TypeError: Cannot read properties of undefined (reading ***)
MySQL advanced learning notes (III)
DotNet圈里一个优秀的ORM——FreeSql
What website can you find English literature on?
sysdig分析容器系统调用
Understanding and application of least square method
随机推荐
MySQL advanced learning notes (III)
秒杀系统设计
Blue decides red - burst CS teamserver password
Array de duplication
Briefly talk about other uses of operation and maintenance monitoring
[reading notes] phased summary of writing reading notes
130 pages of PPT from the brick boss introduces the new features of Apache spark 3.2 & 3.3 in depth
Basic use of shell script
Introduction of UART, RS232, RS485, I2C and SPI
Go自定义排序
Pytorch 20 realizes corrosion expansion based on pytorch
AcWing_188. 武士风度的牛_bfs
v8
Seckill system design
Nc20806 District interval
写论文可以去哪些网站搜索参考文献?
Chapter 4 of getting started with MySQL: data types stored in data tables
Where can I check the foreign literature of economics?
sysdig分析容器系统调用
Install docker and use docker to install MySQL