一、作用
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[root@localhost shell]#
建立一個test2.txt,如下
[root@localhost shell]# cat test2.txt 星期一星期二星期三星期四星期五星期六星期日[root@localhost shell]#
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]#
菜鳥一枚,如有錯誤,多多指教。。。
轉載自https://blog.csdn.net/u011003120/article/details/52190187