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

【Linux 基礎】第五週作業詳解:正則表達式與 find 查找實戰

本週作業聚焦於 egrep 正則匹配與 find 檔案查找的綜合應用,以下逐題解析。

1. 顯示 root、fedora 或 user1 用戶的預設 shell

# egrep '^(root|fedora|user1)' /etc/passwd | cut -d: -f1,7
# awk -F: '/root|fedora|user1/{print $1" ",$7}' /etc/passwd

2. 找出某單詞後接一組小括號的行(形如 hello())

# egrep -o '\<[[:alpha:]]+\>\(\)' /etc/rc.d/init.d/functions

3. 用 echo 輸出絕對路徑,再用 grep 取出基名與路徑名

# echo /etc/sysconfig/network-scripts/ifcfg-eth0 | grep -o '^/.*/'   ### 路徑名
# echo /etc/sysconfig/network-scripts/ifcfg-eth0 | grep -o '[^/]\+$'  ### 基名

4. 找出 ifconfig 結果中 1-255 之間的數字

# ifconfig | egrep -o '[1-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-9]'

5. 挑戰題:匹配合理 IP 位址

# ifconfig | egrep -o '(([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-9])\.){3}[0-9]{1,3}'

6. 挑戰題:匹配所有郵件位址

# egrep -o '[[:alnum:]]+@[[:alnum:]]+(\.[a-z]+){1,}' /tmp/mailtest

7. 查找 /var 下屬主 root、屬組 mail 的檔案

# find /var/ -user root -a -group mail -ls

8. 查找沒有屬主或屬組的檔案(可加 -atime -3 限三天內訪問)

# find / -nouser -o -nogroup

9. 查找 /etc 下所有用戶都有寫權限的檔案

# find /etc/ -perm -222

10. 查找 /etc 下大於 1M 且為普通檔案者

# find /etc/ -size +1M -type f

11. 查找 /etc/init.d 下所有用戶有執行權限、其他用戶有寫權限的檔案

# find /etc/init.d/ -perm -113 -ls

12. 查找 /usr 下不屬於 root、bin 或 hadoop 的檔案

# find /usr/ -not \( -user root -o -user bin -o -user hadoop \)

13. 查找 /etc 下至少有一類用戶沒有寫權限的檔案

# find /etc/ ! -perm -222

14. 查找 /etc 下最近一週內容被修改、且不屬於 root 或 hadoop 的檔案

# find /etc/ -mtime -7 -not \( -user root -o -user hadoop \)

這些題目涵蓋了正則表達式的字元匹配、邊界處理,以及 find 依屬主、權限、大小、時間進行精準查找的經典用法。

Copyright © Linux教程網 All Rights Reserved