Linux cut用法

来源:互联网 发布:dictionary软件下载 编辑:程序博客网 时间:2024/05/16 02:31

一、作用

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,如下

557adfhgbcd5464b135465453456233546576

新建一个test2.txt,如下

星期一星期二星期三星期四星期五星期六星期日

1) -b

1.剪切单个字节

如下,只剪切txt中的每一行的第一个字节

[root@localhost shell]# cut -b 1 test1.txt 5b12[root@localhost shell]# 

2.剪切多个字节

剪切多个字符有很多方式, 
如 -b 1,3,5 //剪切每一行第 1 3 5个字符 (示例1) 
如 -b 1-5 //剪切每一行第 1-5 个字符 (示例2) 
如 -b -5 //剪切每一行第 1-5 个字符 (示例3) 
如 -b 3- //剪切每一行第 3个字符以后的 (示例4)

示例1:

[root@localhost shell]# cut -b 1,3,5 test1.txt 57dbd4156234[root@localhost shell]# 

示例2:

[root@localhost shell]# cut -b 1-5 test1.txt 557adbcd541354623354[root@localhost shell]# 

示例3:
[root@localhost shell]# cut -b -5 test1.txt 557adbcd541354623354[root@localhost shell]# 

示例4:

[root@localhost shell]# cut -b 3- test1.txt 7adfhgd5464b54654534563546576[root@localhost shell]# 

3.剪切字符

首先按照上面的例子对test2.txt进行操作,看有什么现象

[root@localhost shell]# cut -b 2 test2.txt �������[root@localhost shell]# 

出现了乱码的现象,因为-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 星期一星期二星期三星期四星期五星期六星期日[root@localhost shell]# 

2) -c

-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]# 

3)-f

上面的-b -c 只是针对于格式固定的数据中剪切,但是对于一些格式不固定的,就没有办法获取到我们想要的数据,因此便有了 -f 域的概念。

示例1:

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

例如将上面的第一个 : 前面的字符给剪切出来,那么我们就可以使用 -d 命令,指定其分割符为 : 然后再选取第一个域内的内容即可,如下

[root@localhost shell]# cat /etc/passwd | head -n 3 | cut -d : -f 1rootbindaemon[root@localhost shell]# 

示例2: 
剪切ip地址,如下:

[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 2192.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'


现在想获取abcd和efgh,我们可以简单地用cut工具来获取:
fstr=`echo $info | cut -d ; -f 1`sstr=`echo $info | cut -d ; -f 2`


0 0
原创粉丝点击