大数据中常用脚本--cut

1.简介

1.1 国际惯例

按照国际惯例先来理论的介绍。

cut是在Linux里非常常用的一个命令,cut命令是一个选取命令,其功能是将文件中的每一行”字节” ”字符” ”字段” 进行剪切,选取我们需要的,并将这些选取好的数据输出至标准输出。执行过程:选取命令通常是针对一行一行的数据来进行分析的, 并不是整篇信息分析。

2.常用选项

使用时的一般格式:

cut -[n]b file 
cut -c file 
cut -d[分隔符] -f[域] file

素材:

[root@localhost shell]# cat test1.txt 
557adfhg
bcd5464b
135465453456
233546576
[root@localhost shell]# cat test2.txt 
星期一
星期二
星期三
星期四
星期五
星期六
星期日

2.1 cat的-b(bytes)

以字节为单位进行分割。这些字节位置将忽略多字节字符边界,除非也指定了 -n 标志。 切txt中的每一行的第一个字节: 

[root@localhost shell]# cut -b 1 test1.txt 
5
b
1
2
剪切多个字符有很多方式, 
如 -b 1,3,5 //剪切每一行第 1 3 5个字符 (示例1) 
如 -b 1-5 //剪切每一行第 1-5 个字符 (示例2) 
如 -b -5 //剪切每一行第 1-5 个字符 (示例3) 

如 -b 3- //剪切每一行第 3个字符以后的 (示例4)

[root@localhost shell]# cut -b 1,3,5 test1.txt 
57d
bd4
156
234
[root@localhost shell]# cut -b 1-5 test1.txt 
557ad
bcd54
13546
23354
[root@localhost shell]# cut -b -5 test1.txt 
557ad
bcd54
13546
23354
[root@localhost shell]# cut -b 3- test1.txt 
7adfhg
d5464b
5465453456
3546576

2.2 cat的-n和-c剪切字符

首先按照上面的例子对test2.txt进行操作出现了乱码的现象,因为-b 只是针对字节进行裁剪,对一个汉字进行字节裁剪,得到的结果必然是乱码,若想使用 -b 命令对字节进行裁剪,那么则需要使用 -n 选项,此选项的作用是取消分割多字节字符。

[root@localhost shell]# cut -nb 3 test2.txt 
星
星
星
星
星
星
[root@localhost shell]# cut -nb 3,6  test2.txt 
星
星期
星期
星期
星期
星期
星期
[root@localhost shell]# cut -nb 3,6,9  test2.txt 
星期
星期二
星期三
星期四
星期五
星期六
星期日
[root@localhost shell]# cut -nb 3,6,9,12  test2.txt 
星期一
星期二
星期三
星期四
星期五
星期六
星期日

-c的作用就是剪切字符,和上面的 -nb 有些类似:

[root@localhost shell]# cut -c 1 test2.txt 
星
星
星
星
星
星
[root@localhost shell]# cut -c 2 test2.txt 
星
期
期
期
期
期
期
[root@localhost shell]# cut -c 1-3 test2.txt 
星期
星期二
星期三
星期四
星期五
星期六
星期日

2.3 cat的-f格式不固定的剪切

上面的-b -c 只是针对于格式固定的数据中剪切,但是对于一些格式不固定的,就没有办法获取到我们想要的数据,因此便有了 -f 域的概念。字符给剪切出来,那么我们就可以使用 -d 命令,指定其分割符为 : 然后再选取第一个域内的内容即可,如下:

[root@localhost shell]# cat /etc/passwd | head -n 3
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
[root@localhost shell]# cat /etc/passwd | head -n 3 | cut -d : -f 1
root
bin
daemon

猜你喜欢

转载自blog.csdn.net/Learn_ZhangK/article/details/80284546