在開發過程中,有時需要快速列出某個資料夾下的所有檔案路徑,例如批次處理、建立索引、或確認部署內容。以下整理 Linux 和 Windows 的常用方法。
Linux / macOS:使用 find
基本用法
1
2
3
4
5
|
# 列出當前目錄下所有檔案(不含目錄)
find . -type f
# 輸出到文字檔
find . -type f > filepath.txt
|
-type f 表示只列出檔案(file),不包含目錄(directory)。
常用參數說明
| 參數 |
說明 |
-type f |
只列出一般檔案 |
-type d |
只列出目錄 |
-name "*.txt" |
只列出符合名稱模式的檔案 |
-maxdepth N |
最多搜尋 N 層深度 |
-mindepth N |
最少從第 N 層開始 |
-not / ! |
排除符合條件的項目 |
-size +1M |
找出大於 1MB 的檔案 |
-newer file.txt |
找出比 file.txt 更新的檔案 |
過濾特定類型的檔案
1
2
3
4
5
6
7
8
|
# 只列出 .txt 檔案
find . -name "*.txt" -type f
# 只列出 .js 和 .ts 檔案
find . \( -name "*.js" -o -name "*.ts" \) -type f
# 找出大於 1MB 的檔案
find . -type f -size +1M
|
排除特定目錄
1
2
3
4
5
6
7
8
9
|
# 排除 .git 目錄
find . -not -path "./.git/*" -type f
# 排除多個目錄
find . -not -path "./.git/*" -not -path "./node_modules/*" -type f
# 使用 -prune(效能較好)
find . -path "./.git" -prune -o -type f -print
find . \( -path "./.git" -o -path "./node_modules" \) -prune -o -type f -print
|
配合 xargs 批次處理
1
2
3
4
5
|
# 找到所有 .log 檔案並刪除
find . -name "*.log" -type f | xargs rm
# 找到所有 .js 檔案並用 grep 搜尋字串
find . -name "*.js" -type f | xargs grep "TODO"
|
Windows:CMD 指令
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# 列出所有檔案(遞迴)
dir /a-d /s /b
# 各參數說明:
# /a-d 只列出非目錄項目(即檔案)
# /s 遞迴搜尋子目錄
# /b 只顯示路徑,不顯示其他資訊
# 輸出到文字檔
dir /a-d /s /b > filepath.txt
# 只列出特定類型
dir /a-d /s /b *.txt
|
Windows:PowerShell(推薦)
PowerShell 的 Get-ChildItem 功能更強大且輸出格式更友善:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# 列出所有檔案(遞迴)
Get-ChildItem -Recurse -File
# 只列出路徑
Get-ChildItem -Recurse -File | Select-Object FullName
# 輸出到文字檔
Get-ChildItem -Recurse -File | Select-Object -ExpandProperty FullName | Out-File filepath.txt
# 過濾特定副檔名
Get-ChildItem -Recurse -File -Filter "*.txt"
# 排除特定目錄
Get-ChildItem -Recurse -File | Where-Object { $_.FullName -notmatch "node_modules|\.git" }
# 相對路徑(較簡短)
Get-ChildItem -Recurse -File | Resolve-Path -Relative
|
實用範例:建立檔案清單
Linux:建立專案的 PHP 檔案清單
1
|
find . -name "*.php" -not -path "./vendor/*" -type f | sort > php_files.txt
|
PowerShell:找出大型檔案
1
2
3
4
|
Get-ChildItem -Recurse -File |
Where-Object { $_.Length -gt 1MB } |
Sort-Object Length -Descending |
Select-Object FullName, @{Name='Size(MB)';Expression={[math]::Round($_.Length/1MB, 2)}}
|
計算各類型檔案數量
1
2
|
# Linux:依副檔名統計檔案數
find . -type f | sed 's/.*\.//' | sort | uniq -c | sort -rn
|