2017-06-22 137 views
2

我想寫一個代碼,它將顯示我定義的文件的路徑。比如我有兩個文件批處理腳本返回文件的路徑

  1. d:\測試\ ExecuteScript.bat
  2. d:\ document.txt的

我希望在我的腳本定義文件名 「文檔.txt」並返回「D:\ Test \ ExecuteScript.bat」。我也曾嘗試下面的代碼:

用於/ R %% X IN(*文檔.txt)做回聲 「%% X」

然而,這僅在文檔工作.TXT是一個文件夾內,而ExecuteScript.bat是文件夾外部,〔實施例:

  1. d:\ ExecuteScript.bat
  2. d:\測試\ document.txt的

我已經搜索了許多在線解決方案,但其中許多需要我把C:\放在我不想要的代碼的前面。非常感謝,並提前抱歉我的英語不好。

+1

'爲/ R 「d:\」 %% X中(「* document.txt」)會回顯「%%〜x」';如果你正在使用同一個驅動器:'for/R「\」%% x in(「* document.txt」)do echo「%%〜x」'就足夠了;或者你想搜索*所有*驅動器? – aschipfl

+0

'for/r「d:\ tests」%% x in(「* document.txt」)do echo「%% x」'? – npocmaka

+0

@aschipfl你是否有能夠在所有驅動器中搜索的代碼? – thompsonrapier

回答

1

告訴for /R從哪裏開始搜索文件,只需說出背後/R路徑:如果您在同一驅動器上工作,你搜索

for /R "D:\" %%x in ("*document.txt") do echo "%%~x" 

,以下就足夠了:

for /R "\" %%x in ("*document.txt") do echo "%%~x" 

以下是for的幫助摘錄,當您輸入for /?時:

FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters] 

    Walks the directory tree rooted at [drive:]path, executing the FOR 
    statement in each directory of the tree. If no directory 
    specification is specified after /R then the current directory is 
    assumed. If set is just a single period (.) character then it 
    will just enumerate the directory tree. 

如果你想在所有驅動器進行搜索,你可以做到以下幾點:

rem // Loop through all drive letters: 
for %%d in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
    rem // Temporarily try to change to root of current drive: 
    pushd "%%d:\" 2> nul && (
     rem // Drive found, so search it for matching files: 
     for /R %%x in ("*document.txt") do echo "%%~x" 
     popd 
    ) 
)