cut命令 – 连接文件并打印到标准输出设备上

来自:网络
时间:2020-09-24
阅读:

cut命令有两个主要的功能,第一是显示文件内容,第二是连接多个或多个文件。

若不指定file参数,该命令将读取标准输入。 必须指定 -b、-c 或 -f 标志之一。

语法格式:cut [参数] [文件]

常用参数:

-b以字节为单位进行分割 ,仅显示行中指定直接范围的内容
-c以字符为单位进行分割 , 仅显示行中指定范围的字符
-d自定义分隔符,默认为制表符”TAB”
-f显示指定字段的内容 , 与-d一起使用
-n取消分割多字节字符
--complement补足被选择的字节、字符或字段
--out-delimiter指定输出内容是的字段分割符

参考实例

假设有一个学生报表信息,包含 No、Name、Mark、Percent:

[root@linuxcool ~]# cat student.txt No Name Mark Percent 01 tom   69   91 02 jack  71   87 03 alex  68   98  

使用 -f 选项提取指定字段(这里的 f 参数可以简单记忆为 --fields的缩写):

[root@linuxcool ~]# cut -f 2 student.txt Nametom jackalex 

--complement选项提取指定字段之外的列(打印除了第二列之外的列):

[root@linuxcool ~]# cut -f2 --complement student.txt No Mark Percent 01  69   91 02  71   87 03  68   98 

使用 -d选项指定字段分隔符:

[root@linuxcool ~]# cat student2.txt No;Name;Mark;Percent 01;tom;69;91 02;jack;71;87 03;alex;68;98 
[root@linuxcool ~]# cut -f2 -d";" student2.txt Name tom jack alex 
[root@linuxcool ~]# cat test.txt abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz 

打印第 1 个到第 3 个字符:

[root@linuxcool ~]# cut -c1-3 test.txt abc abc abc abc abc 

注意:-b 表示字节;-c 表示字符;-f 表示定义字段。

N-:从第 N 个字节、字符、字段到结尾; N-M :从第 N 个字节、字符、字段到第 M 个(包括 M 在内)字节、字符、段; -M:从第 1 个字节、字符、字段到第 M 个(包括 M 在内)字节、字符、字段。

打印前 2 个字符:

[root@linuxcool ~]# cut -c-2 test.txt ab ab ab ab ab 

打印从第 5 个字符开始到结尾:

[root@linuxcool ~]# cut -c5- test.txt efghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz 
返回顶部
顶部