「Linux文件及目錄管理」通配符與文件名
知識點解析
通配符是Linux中用于匹配文件名的特殊字符,能高效處理批量文件操作。
常見通配符包括:
*
:匹配任意字符序列(包括空字符)touch a b ab a123 # 創建測試文件 ls a* # 匹配a, ab, a123
?
:精確匹配單個字符touch file1.txt file2.txt file10.txt ls file?.txt # 僅匹配file1.txt, file2.txt
[]
:匹配指定范圍內的單個字符(如[a-z]
)ls [a-c]*.txt # 匹配以a/b/c開頭的.txt文件 ls [0-9][0-9].txt # 匹配兩位數字開頭的.txt文件
[^]
:匹配不在指定范圍內的字符ls [^a]*.txt # 匹配不以a開頭的.txt文件
特殊場景處理
- 隱藏文件匹配:
.*
(需謹慎使用) - 遞歸匹配:需結合
find
命令 - 大小寫敏感:
[A-Z]
和[a-z]
需分開處理
適用場景:
- 批量刪除日志文件
- 快速定位特定格式文件
- 組合命令實現復雜篩選
案例解析
案例:批量刪除舊日志文件
# 刪除當前目錄下所有.log文件(保留最近3天)
find . -name "*.log" -mtime +3 -exec rm {} \;# 使用通配符簡化(僅適用于當前目錄)
rm *.log
解析:
find
命令結合-name
和-mtime
實現精準篩選- 通配符
*.log
直接匹配所有.log文件,但無法處理子目錄
案例:重命名特定格式文件
# 創建測試文件
touch file{1..5}.txt
ll *.txt
# -rw-r--r-- 1 root root 0 6月 21 09:10 file1.txt
# -rw-r--r-- 1 root root 0 6月 21 09:10 file2.txt
# -rw-r--r-- 1 root root 0 6月 21 09:10 file3.txt
# -rw-r--r-- 1 root root 0 6月 21 09:10 file4.txt
# -rw-r--r-- 1 root root 0 6月 21 09:10 file5.txt# 將所有.txt文件重命名為.bak
find</