cut命令
cut是一个字符选取命令,从文件的每一行剪切字节、字符和字段并将这些字节、字符和字段至标准输出。
语法格式为:
cut [bcdfn]... file...
主要参数
-b :以字节为单位进行分割。这些字节位置将忽略多字节字符边界,除非也指定了 -n 标志。
-c :以字符为单位进行分割。
-d :自定义分隔符,默认为制表符。
-f :与-d一起使用,指定显示哪个区域。
-n :取消分割多字节字符。仅和 -b 标志一起使用。
实例1:取出/etc/passwd中的用户名并且shell为/bin/bash
# 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:以字节为定位截取
[root@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) [root@xc test]# who | cut -b 4 t t t [root@xc test]# who | cut -b -3 roo roo roo [root@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) [root@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:以字符为定位标识
[root@xc test]# cat xinqi.txt 星期一 星期二 星期三 星期四
-b:以字节为单位,对多字节字符支持不好,输出不了,空白
[root@xc test]# cat xinqi.txt | cut -b 3
-c:可以支持多字节字符
[root@xc test]# cat xinqi.txt | cut -c 3 一 二 三 四
-n:用于告诉cut不要将多字节拆开,与b结合
[root@xc test]# cat xinqi.txt | cut -nb 3 星 星 星 星 [root@xc test]# cat xinqi.txt | cut -nb 1,2,3 星 星 星 星 [root@xc test]# cat xinqi.txt | cut -nc 1,2,3 星期一 星期二 星期三 星期四 [root@xc test]# cat xinqi.txt | cut -nc 2 期 期 期 期
-f:指定间隔符
对于那些非固定格式的信息,-c,和-b就不好用了,
cut命令提供了这样的提取方式,具体的说就是设置“间隔符”进行提取
[root@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 [root@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 [root@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:可以看出文本是否到了结尾处
[root@xc test]# cat 1.txt hello good morning yes who are you @ [root@xc test]# sed -n l 1.txt hello $ $ good morning$ yes$ who are you @$
截取空格:
[root@xc test]# cat 1.txt | cut -d' ' -f1 hello good yes who
注:两个单引号之间可确实要有一个空格,在-d后面只能加一个空格,不要加多个,因为cut只允许间隔符是一个字符。
参考:http://www.cnblogs.com/dong008259/archive/2011/12/09/2282679.html
转载于:https://blog.51cto.com/airs0sec/1687774