標籤:
cut命令可以從一個文字檔或者文字資料流中提取文本列。
cut文法
[[email protected] ~]# cut -d ‘分隔字元‘ -f fields <==用於有特定分隔字元
[[email protected] ~]# cut -c 字元區間 <==用於排列整齊的資訊
選項與參數:
-d :後面接分隔字元。與 -f 一起使用;
-f :依據 -d 的分隔字元將一段資訊分割成為數段,用 -f 取出第幾段的意思;
-c :以字元 (characters) 的單位取出固定字元區間;
PATH 變數如下
[[email protected] ~]# echo $PATH
/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/X11R6/bin:/usr/games
# 1 | 2 | 3 | 4 | 5 | 6 | 7
將 PATH 變數取出,我要找出第五個路徑。
#echo $PATH | cut -d ‘:‘ -f 5
/usr/local/bin
將 PATH 變數取出,我要找出第三和第五個路徑。
#echo $PATH | cut -d ‘:‘ -f 3,5
/sbin:/usr/local/bin
將 PATH 變數取出,我要找出第三到最後一個路徑。
echo $PATH | cut -d ‘:‘ -f 3-
/sbin:/usr/sbin:/usr/local/bin:/usr/X11R6/bin:/usr/games
將 PATH 變數取出,我要找出第一到第三個路徑。
#echo $PATH | cut -d ‘:‘ -f 1-3
/bin:/usr/bin:/sbin:
將 PATH 變數取出,我要找出第一到第三,還有第五個路徑。
#echo $PATH | cut -d ‘:‘ -f 1-3,5
/bin:/usr/bin:/sbin:/usr/local/bin
實用例子:只顯示/etc/passwd的使用者和shell
#cat /etc/passwd | cut -d ‘:‘ -f 1,7
root:/bin/bash
daemon:/bin/sh
bin:/bin/sh
截取指定個數的字元
$ a=`echo root:x:0:0:root:/root:/bin/bash | cut -c 2-5 ` // 截取第2到第5個字元
$ echo $a
oot:
$ a=`echo root:x:0:0:root:/root:/bin/bash | cut -c -2 ` // 截取前兩個字元
$ echo $a
ro
$ a=`echo root:x:0:0:root:/root:/bin/bash | cut -c 2- ` // 截取第2個以後的
$ echo $a
oot:x:0:0:root:/root:/bin/bash
指定檔案,最後一個參數是檔案名稱
$ > cat cut_test.txt
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
$ > cut -d : -f 1,6 ./cut_test.txt
root:/root
bin:/bin
daemon:/sbin
adm:/var/adm
或者用cut -d : -f 1,6 cut_test.txt 和 cat cut_test.txt | cut -d : -f 1,6 都可以
shell -- cut用法