Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux Basic 5:正規表達式與 find 命令實作

本單元整理正規表達式與 find 命令的常見練習,包含查詢使用者 shell、比對函式名稱、擷取路徑、匹配 IP、郵件地址,以及依權限與時間查找檔案。

一、查詢使用者 shell

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 "/.*/"

四、比對 1 到 255 的數字

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'

五、匹配合理 IP

"\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 常用範例

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 的強項在於可組合屬主、屬組、權限、大小、類型與時間條件,適合日常系統排查與批次處理。

Copyright © Linux教程網 All Rights Reserved