【Linux】常用命令
阿新 • • 發佈:2021-08-13
Linux 常用命令記錄
常用命令
查詢檔案
find . # 列出當前目錄及子目錄下所有檔案和資料夾 find . -type f # 當前目錄搜尋所有檔案 find /home -name "*.txt" # 在/home目錄下查詢以.txt結尾的檔名 find /home -iname "*.txt" # 在/home目錄下查詢以.txt結尾的檔名, 忽略大小寫 find . -name "*.txt" -o -name "*.pdf" # 當前目錄及子目錄下查詢所有以.txt和.pdf結尾的檔案 find /usr/ -path "*local*" # 檔案路徑或檔案包含path find . -regex ".*\(\.txt\|\.pdf\)$" # 正則表示式匹配檔案路徑 find . -iregex ".*\(\.txt\|\.pdf\)$" # 正則表示式匹配檔案路徑, 並忽略大小寫 find /home ! -name "*.txt" # 查詢/home 不已.txt結尾 find . -maxdepth 3 -type f # 向下最大深度限制為3 find . -type f -atime -7 # 最近七天內被訪問過的所有檔案 find . -type f -atime +7 # 超過七天內被訪問過的所有檔案 find . -type f -size +10k # 搜尋大於10KB的檔案
文字搜尋
grep "match_pattern" file_name # 搜尋指定檔案,返回包含“match_pattern” 的文字行 grep "match_pattern" file_name -n # 搜尋指定檔案,返回包含“match_pattern” 的文字行, 並輸出行數 grep "match_pattern" file_1 file_2 file_3 # 搜尋多個檔案,返回包含“match_pattern” 的文字行 grep "match_pattern" file_name -v # 輸出除之外的所有行 grep "match_pattern" file_name --color=auto # 標記匹配顏色 --color: never、always、auto grep -E "[1-9]+" file_name # 正則匹配查詢 grep -E "[1-9]+" -o file_name # 只輸出文件匹配部分 grep "text" . -r -n # 遞迴搜尋 grep "match_pattern" file_name -A 3 # 匹配結果並輸出之後3行 grep "match_pattern" file_name -B 3 # 匹配結果並輸出之前3行
統計檔案/資料夾大小
du -sh . # 顯示當前目錄大小 du -sh * # 顯示各個檔案和目錄大小 du -sh * | sort -rh # 檔案從大到小排序 du --time # 顯示目錄或該目錄子目錄下所有檔案的最後修改時間 du -sh * --time # 顯示當前目錄各個檔案/資料夾最後修改時間 du -sh ./*/ # 只顯示當前目錄下子目錄的大小
組合使用
find . -type f -name "*.log" | xargs grep "warning" # 查詢符合條件檔案,並搜尋關鍵字
find . -name "*.py" | xargs cat | grep -v ^$ |wc -l # 程式碼行數統計, 排除空行
grep -i "warning" > result.log # 查詢結果寫入檔案