本單元整理正規表達式與 find 命令的常見練習,包含查詢使用者 shell、比對函式名稱、擷取路徑、匹配 IP、郵件地址,以及依權限與時間查找檔案。
for userid in root fedora user1; do
id $userid > /dev/null || useradd $userid
grep "^$userid" /etc/passwd | cut -d: -f1,7
done找出單字後接一組小括號的行:
grep "\<[[:alpha:]]\+\>()" /etc/rc.d/init.d/functions
echo "/etc/rc.d/init.d/functions" | grep -o "[^/]\+$" echo "/etc/rc.d/init.d/functions" | grep -o "/.*/"
ifconfig | grep -E -o '\b(2[0-4][0-9])\b|\b(25[0-5])\b|\b(1[0-9][0-9])\b|\b([1-9][0-9])\b|\b([1-9])\b'
"\b(([1-9])|([1-9][0-9])|(1[0-9]+)|(2[0-3][0-9]))\.(([0-9])|([1-9][0-9])|(1[0-9]+)|(2[0-4][0-9])|(25[0-5]))\.(([0-9])|([1-9][0-9])|(1[0-9]+)|(2[0-4][0-9])|(25[0-5]))\.(([1-9])|([1-9][0-9])|(1[0-9]+)|(2[0-4][0-9])|(25[0-4]))\b"
此模式排除主機位全 0 與全 1 的情況。
'^([[:alnum:]]{0,}[-_]?[[:alnum:]]{0,})@(([[:alnum:]]{0,}[-_]?[[:alnum:]]{0,})\.){1,5}([[:alnum:]]{0,}[-_]?[[:alnum:]]{0,})$'find /var -user root -group mail find / -nouser -o -nogroup find /etc -perm /222 find /etc -type f -size +1M find /etc/init.d -perm /113 find /usr -not -user root -a -not -user bin find /etc -mtime -7 -not -user root
find 的強項在於可組合屬主、屬組、權限、大小、類型與時間條件,適合日常系統排查與批次處理。