cut命令是一个选取命令,其功能是将文件中的每一行”字节” ”字符” ”字段” 进行剪切,选取我们需要的,并将这些选取好的数据输出至标准输出
cut -[n]b file
cut -c file
cut -d[分隔符] -f[域] file
-b(bytes) :以字节为单位进行分割。这些字节位置将忽略多字节字符边界,除非也指定了 -n 标志。
-c(characters) :以字符为单位进行分割。
-d :自定义分隔符,默认为制表符。
-f(filed) :与-d一起使用,指定显示哪个区域。
-n :取消分割多字节字符。仅和 -b 标志一起使用。如果字符的最后一个字节落在由 -b 标志的 List 参数指示的
范围之内,该字符将被写出;否则,该字符将被排除。
新建一个test1.txt,如下
557adfhg
bcd5464b
135465453456
233546576
星期一
星期二
星期三
星期四
星期五
星期六
星期日
如下,只剪切txt中的每一行的第一个字节
[root@localhost shell]# cut -b 1 test1.txt
5
b
1
2
[root@localhost shell]#
剪切多个字符有很多方式,
如 -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]#
[root@localhost shell]# cut -b 1-5 test1.txt
557ad
bcd54
13546
23354
[root@localhost shell]#
[root@localhost shell]# cut -b -5 test1.txt
557ad
bcd54
13546
23354
[root@localhost shell]#
[root@localhost shell]# cut -b 3- test1.txt
7adfhg
d5464b
5465453456
3546576
[root@localhost shell]#
首先按照上面的例子对test2.txt进行操作,看有什么现象
[root@localhost shell]# cut -b 2 test2.txt
�
�
�
�
�
�
�
[root@localhost shell]#
[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
星期一
星期二
星期三
星期四
星期五
星期六
星期日
[root@localhost shell]#
-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
星期
星期二
星期三
星期四
星期五
星期六
星期日
[root@localhost shell]#
上面的-b -c 只是针对于格式固定的数据中剪切,但是对于一些格式不固定的,就没有办法获取到我们想要的数据,因此便有了 -f 域的概念。
示例1:
[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]#
[root@localhost shell]# cat /etc/passwd | head -n 3 | cut -d : -f 1
root
bin
daemon
[root@localhost shell]#
[root@localhost shell]# ifconfig eth0 | grep "inet addr"
inet addr:192.168.1.199 Bcast:192.168.1.255 Mask:255.255.255.0
[root@localhost shell]# ifconfig eth0 | grep "inet addr" | cut -d : -f 2
192.168.1.199 Bcast //以 : 为分隔符,选取第二个域里面的内容,输出
[root@localhost shell]# ifconfig eth0 | grep "inet addr" | cut -d : -f 2 | cut -d ' ' -f 1
192.168.1.199 //以空格为分割符,选取第一个域内的内容,输出
[root@localhost shell]#
4)实现对字符串的分割
我们有这样一个字符串:
info='abcd;efgh'
fstr=`echo $info | cut -d ; -f 1`
sstr=`echo $info | cut -d ; -f 2`