Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Linux Shell 文字處理指令技巧大全:find、grep、sed、awk 一把抓

find:條件式尋找檔案

可用正則比對(find -regex,注意其規則與常見正則略有差異);依時間搜尋時,- 表示小於、+ 表示大於:

find . [-atime | -mtime | -ctime] [+|-]n[smhdw]

依大小搜尋(單位 k、M、G):

find . -type f -size +2k

依權限搜尋:-perm mode 為嚴格相等;-perm -mode 表示權限位轉二進位後,所有為 1 的位元都必須符合;-perm +mode 則只需任一 1 位元符合,兩者都不理會 0 位。

把找到的檔案複製到 Documents,或交給自訂腳本處理:

find . -type f -mtime +10 -name "*.txt" -exec cp {} ~/Documents/ \;
find . -type f -exec ./commands.sh {} \;

grep:抽取符合的行

-o 只輸出比對到的文字、-v 只輸出未比對到的行、-c 統計次數、-n 印出行號、-i 忽略大小寫、-l 只印檔名。

grep "Jonathan" . -R -n          # 遞迴搜尋並顯示行號
grep test . -R -n --colour       # 命中處高亮
grep -e "test" -e "image" . -R -n --colour   # 多模式比對

xargs:把輸入變成參數

把 stdin 的內容整理後當成下一個指令的參數,-0 可讓特殊字元被視為一般字元。

sort 與 uniq:排序與去重

sort 常用 -n(數字排序)、-d(字典序)、-r(逆序)、-k N(第 N 欄)。uniq 需先排序才準:

sort unsort.txt | uniq        # 去除重複行
sort unsort.txt | uniq -c     # 統計各行出現次數
sort unsort.txt | uniq -d     # 只列出重複行

tr:字元轉換

echo 12345 | tr '0-9' '9876543210'
tr '[:lower:]' '[:upper:]'

常用字元類別:alnum(字母加數字)、alpha、digit、space、lower、upper、cntrl(控制字元)、print(可列印字元),用法為 tr [:class:] [:class:]。

paste 與 wc

paste file1 file2      # 逐列拼接兩個檔案
wc -l file             # 行數
wc -w file             # 單字數
wc -c file             # 字元數

sed:串流編輯器

sed 's/text/replace_text/' file      # 每行只換第一處
sed 's/text/replace_text/g' file     # 全行替換
sed -i 's/text/replace_text/g' file  # 直接改寫原檔
sed '/^$/d' file                     # 移除空白行

已比對到的字串可用 & 引用;括號中的子字串則以 \1 引用:

echo this is en example | sed 's/\w+/[&]/g'
sed 's/hello([0-9])/\1/' file

sed 通常用單引號,改用雙引號時運算式中的變數會被求值。

awk:逐行處理的報表工具

結構為 awk 'BEGIN{...} {...} END{...}'。內建變數:NR 目前行號、NF 目前行欄位數、$0 整行內容、$1、$2 為各欄。

awk '{print $2, $3}' file          # 印第二、三欄
awk 'END {print NR}' file          # 統計行數
awk 'NR < 5 {print $0}' file       # 印行號小於 5 的行
awk 'NR==1,NR==4 {print $0}' file  # 印第一與第四行
awk '/text/ {print $0}'            # 含 text 的行
awk '!/linux/ {print $0}'          # 不含 linux 的行
Copyright © Linux教程網 All Rights Reserved