find -maxdepth 0 沒有回傳任何輸出

find -maxdepth 0 沒有回傳任何輸出

我想了解如何使用find -maxdepth 0選項。

我有以下目錄結構。

--> file1
--> parent
          --> child1
                   --> file1
                   --> file2
          --> child2
                   --> file1
                   --> file2
          --> file1

現在,我執行find如下命令。

find ./parent -maxdepth 0 -name "file1"
find ./ -maxdepth 0 -name "file1"
find . -maxdepth 0 -name "file1"

如果沒有上述find命令,文件1被返回。

從 的手冊頁中find,我看到以下資訊。

-maxdepth 0 表示僅將測試和操作應用於命令列參數。

我搜尋了一些帶有-maxdepth 0選項的範例,但找不到任何合適的範例。

我的find版本是,

find --version
find (GNU findutils) 4.4.2

有人可以提供我一些關於哪些案例-maxdepth 0選項有用的指示嗎?

編輯

當我執行以下命令時,我得到文件1被列出兩次。這是打算這樣運作嗎?

find . file1 -maxdepth 1 -name "file1"
./file1
file1

答案1

讓我們假設我們file1在當前目錄中。然後:

$ find . -maxdepth 0 -name "file1"
$ find . file1 -maxdepth 0 -name "file1"
file1

現在,讓我們看看什麼文件狀態:

-maxdepth 0 意味著僅將測試和操作應用於命令列參數。

在上面的第一個範例中,只有目錄.列在命令列上。自從.沒有名稱file1,輸出中未列出任何內容。在上面的第二個例子中,兩者.和 file1列在命令列上,並且由於file1matches -name "file1",它在輸出中返回。

換句話說,-maxdepth 0意味著不是搜尋目錄或子目錄。相反,僅在命令列上明確列出的文件中尋找匹配的文件。

在您的範例中,命令列上僅列出了目錄,並且沒有一個目錄被命名為file1。因此,沒有輸出。

一般來說,很多檔案和目錄都可以在命令列上命名。例如,這裡我們find在命令列上嘗試一個包含九個檔案和目錄的命令:

$ ls
d1  file1  file10  file2  file3  file4  file5  file6  file7
$ find d1 file1 file10 file2 file3 file4 file5 file6 file7 -maxdepth 0 -name "file1"
file1

重疊路徑

考慮:

$ find . file1 -maxdepth 0 -iname file1
file1
$ find . file1 file1 -maxdepth 0 -iname file1
file1
file1
$ find . file1 file1 -maxdepth 1 -iname file1
./file1
file1
file1

find將遵循命令列上指定的每個路徑並尋找匹配項,即使這些路徑通往同一文件(如 中). file,或即使路徑完全重複(如 中)file1 file1

答案2

如果您想在目錄中非遞歸地尋找檔案(而不是目錄),請使用:

find . -maxdepth 1 -type f -name "file1"
# ./file1

-maxdepth 0 不會搜尋。它只會嘗試匹配您作為參數提供的文件/目錄名稱find

例如,在上面的語句中,使用,maxdepth的值0將嘗試匹配file1.匹配的內容。

然而,傳遞*而不是與.組合-maxdepth 0將使 bash 替換*為當前目錄中的文件列表,這將返回匹配項。

答案3

用法:

John1024 給了一個很好的例子,如何使用-maxdepth 0,所以我只添加信息什麼時候使用它:

那麼,這是什麼原因呢-maxdepth 0?如果你知道名字,你可以下達命令

ls file-* 

好吧,這可能不是你要搜尋的名字。

例子:

touch file-{1..3}
echo "1" > file-1
touch -d @0 file-2

find * -maxdepth 0 -name "file-*" \( -size 1k -o -mtime +10000 \) -ls 
   669266     12 -rw-rw-r--   1 stefan   stefan          2 Mai  4 20:57 file-1
   669270      8 -rw-rw-r--   1 stefan   stefan          0 Jan  1  1970 file-2

我建立了 3 個名為模式檔案-* 的檔案。然後我在no上添加一些內容。 1.重新設定編號的日期。 2 並留下編號。 3 按原樣。

現在,我在大約 1000 個文件中搜尋 1k(第一)或年齡 > 大約 30 年的文件。例如,僅在 3 個文件中。

但是 find * 搜尋當前目錄中的每個文件,因此有點陌生的手冊頁術語,“起點”,而不僅僅是談論目錄。我猜 find 強大的過濾功能導致了搜尋檔案的決定,您知道它們所在的位置($PWD),但您無法使用標準 shell 工具輕鬆過濾其他屬性。

相關內容