正則表達式是描述字元排列與匹配模式的語法規則,主要用在字串的分割、匹配、查找與替換。
正則表達式用來在檔案內容中匹配字串,屬於「包含匹配」,grep、awk、sed 都支援它,靠元字元完成比對。
萬用字元則用來匹配檔名,屬於「完全匹配」。ls、find、cp 不支援正則,只能用 shell 自己的萬用字元:
* 任意多個字元 ? 任意一個字元 [] 中括號內任一字元cut 從每一行擷取指定的位元組、字元或欄位,輸出到標準輸出。
-b 以位元組分割 -c 以字元分割 -d 自訂分隔符(預設為定位字元 Tab) -f 與 -d 併用,指定要顯示第幾欄 -n 不分割多位元組字元,僅與 -b 併用
[root@localhost shell]# cut -f 4 student.txt Mark 85 70 75 90
[root@localhost shell]# cut -d "," -f 4 student.csv Mark 85 70 75 90
[root@localhost shell]# echo "abcdef" | cut -c 3 c
[root@localhost shell]# echo "Shell編程" | cut -nb 8 編 [root@localhost shell]# echo "Shell編程" | cut -nb 11 程
printf '輸出類型輸出格式' 輸出內容
型別:%ns 字串(n 為字元數,省略則全部)、%ni 整數、%m.nf 浮點數(m 為總位數、n 為小數位數,如 %8.2f 為共 8 位、2 位小數)。
格式:\a 響鈴、\b 退格、\f 清屏、\n 換行、\r 回車、\t 水平定位、\v 垂直定位。
[root@localhost ~]# printf '%i %s %i %s %i\n' 1 "+" 2 "=" 3 1 + 2 = 3 [root@localhost ~]# printf '%i-%i-%i %i:%i:%i\n' 2015 12 3 21 56 30 2015-12-3 21:56:30
awk '條件1{動作1} 條件2{動作2}...' 檔名
條件通常用關係運算式(如 x > 10),動作則是格式化輸出或流程控制。
[root@localhost shell]# awk '{print $1 "\t" $4}' student.txt
ID Mark
1 85
2 70
3 75
4 90
[root@localhost shell]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda2 18G 2.4G 14G 15% /
/dev/sda1 289M 16M 258M 6% /boot
tmpfs 411M 0 411M 0% /dev/shm
[root@localhost shell]# df -h | grep "sda1" | awk '{print $5}'
6%
sed 幾乎存在於所有 UNIX 平台,主要用來做選取、替換、刪除與新增。
sed [選項] '[動作]' 檔名 -n 只輸出被 sed 處理過的行 -e 對輸入套用多條 sed 指令 -i 直接把結果寫回原檔 a 在當前行後追加 c 以新字串取代整行 i 在當前行前插入 d 刪除指定行 p 印出指定行 s 字串替換,格式為「行範圍/s/舊/新/g」
# 只印第 2 行 [root@localhost shell]# sed -n '2p' student.txt 1 ming F 85 # 刪除第 2 行 [root@localhost shell]# sed '2d' student.txt ID Name Gender Mark 2 zhang F 70 3 wang M 75 4 li M 90 # 刪除第 2~4 行 [root@localhost shell]# sed '2,4d' student.txt ID Name Gender Mark 4 li M 90 # 第 2 行之後追加 [root@localhost shell]# sed '2a test append' student.txt # 第 2 行之前插入 [root@localhost shell]# sed '2i test insert' student.txt # 取代第 2 行 [root@localhost shell]# sed '2c test replace' student.txt # 把第 2 行的 ming 換成 replace [root@localhost shell]# sed '2s/ming/replace/g' student.txt ID Name Gender Mark 1 replace F 85 2 zhang F 70 3 wang M 75 4 li M 90
注意以上範例都沒有加 -i,所以只輸出到螢幕、原檔不變;要直接改檔才加上 -i。