2017-06-22 136 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 
    ) 
)