|
cut命令
cut是一个字符选取命令,从文件的每一行剪切字节、字符和字段并将这些字节、字符和字段至标准输出。
语法格式为:
cut [bcdfn]... file...
主要参数
-b :以字节为单位进行分割。这些字节位置将忽略多字节字符边界,除非也指定了 -n 标志。
-c :以字符为单位进行分割。
-d :自定义分隔符,默认为制表符。
-f :与-d一起使用,指定显示哪个区域。
-n :取消分割多字节字符。仅和 -b 标志一起使用。
实例1:取出/etc/passwd中的用户名并且shell为/bin/bash
1
2
3
4
5
6
| # cat /etc/passwd | grep '/bin/bash' | cut -d: -f1,7
root:/bin/bash
xc:/bin/bash
mysql:/bin/bash
nagios:/bin/bash
xcroom-01:/bin/bash
|
-b:以字节为定位截取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| [iyunv@xc test]# who
root tty1 2015-07-30 17:59
root pts/3 2015-08-24 00:52 (192.168.0.105)
root pts/4 2015-08-24 01:11 (192.168.0.105)
[iyunv@xc test]# who | cut -b 4
t
t
t
[iyunv@xc test]# who | cut -b -3
roo
roo
roo
[iyunv@xc test]# who | cut -b 3-
ot tty1 2015-07-30 17:59
ot pts/3 2015-08-24 00:52 (192.168.0.105)
ot pts/4 2015-08-24 01:11 (192.168.0.105)
[iyunv@xc test]# who | cut -b -3,3-
root tty1 2015-07-30 17:59
root pts/3 2015-08-24 00:52 (192.168.0.105)
root pts/4 2015-08-24 01:11 (192.168.0.105)
|
-c:以字符为定位标识
1
2
3
4
5
| [iyunv@xc test]# cat xinqi.txt
星期一
星期二
星期三
星期四
|
-b:以字节为单位,对多字节字符支持不好,输出不了,空白
1
| [iyunv@xc test]# cat xinqi.txt | cut -b 3
|
-c:可以支持多字节字符
1
2
3
4
5
| [iyunv@xc test]# cat xinqi.txt | cut -c 3
一
二
三
四
|
-n:用于告诉cut不要将多字节拆开,与b结合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| [iyunv@xc test]# cat xinqi.txt | cut -nb 3
星
星
星
星
[iyunv@xc test]# cat xinqi.txt | cut -nb 1,2,3
星
星
星
星
[iyunv@xc test]# cat xinqi.txt | cut -nc 1,2,3
星期一
星期二
星期三
星期四
[iyunv@xc test]# cat xinqi.txt | cut -nc 2
期
期
期
期
|
-f:指定间隔符
对于那些非固定格式的信息,-c,和-b就不好用了,
cut命令提供了这样的提取方式,具体的说就是设置“间隔符”进行提取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| [iyunv@xc test]# cat /etc/passwd | grep '/bin/bash' | cut -d: -f1-3
root:x:0
xc:x:500
mysql:x:27
nagios:x:501
xcroom-01:x:502
[iyunv@xc test]# cat /etc/passwd | grep '/bin/bash' | cut -d: -f1-3,7
root:x:0:/bin/bash
xc:x:500:/bin/bash
mysql:x:27:/bin/bash
nagios:x:501:/bin/bash
xcroom-01:x:502:/bin/bash
[iyunv@xc test]# cat /etc/passwd | grep '/bin/bash' | cut -d: -f-3
root:x:0
xc:x:500
mysql:x:27
nagios:x:501
xcroom-01:x:502
|
如果遇到空格怎么办
sed -n -I /path/to/filename:可以看出文本是否到了结尾处
1
2
3
4
5
6
7
8
9
10
11
| [iyunv@xc test]# cat 1.txt
hello
good morning
yes
who are you @
[iyunv@xc test]# sed -n l 1.txt
hello $
$
good morning$
yes$
who are you @$
|
截取空格:
1
2
3
4
5
| [iyunv@xc test]# cat 1.txt | cut -d' ' -f1
hello
good
yes
who
|
注:两个单引号之间可确实要有一个空格,在-d后面只能加一个空格,不要加多个,因为cut只允许间隔符是一个字符。
|
|