Batch command to open all files of a certain type

2020-06-16 08:39发布

问题:

I have the following batch command to open files with dtd extension.

REM Open all the static content files
"C:\Program Files (x86)\Notepad++\notepad++.exe" "D:\data\folder1\File1.dtd"
"C:\Program Files (x86)\Notepad++\notepad++.exe" "D:\data\folder1\File2.dtd"
"C:\Program Files (x86)\Notepad++\notepad++.exe" "D:\data\folder2\File1.dtd"
"C:\Program Files (x86)\Notepad++\notepad++.exe" "D:\data\folder2\File2.dtd"
"C:\Program Files (x86)\Notepad++\notepad++.exe" "D:\data\folder3\File1.dtd"
"C:\Program Files (x86)\Notepad++\notepad++.exe" "D:\data\folder3\File2.dtd"

How do I change this batch command to open all files with dtd extension under "D:\data" folder ?

I tried the below code but it does not work

REM Open all the static content files
"C:\Program Files (x86)\Notepad++\notepad++.exe" "D:\data\\*.dtd"

回答1:

You can use the FOR command:

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.

In your case this should work:

FOR /R d:\data %a IN (*.dtd) DO "C:\Program Files (x86)\Notepad++\notepad++.exe" "%a"

Use %%a if you need to run this from a batch file

If you want to use multiple extensions you can separate those with a space

FOR /R d:\data %a IN (*.dtd *.xml *.xslt) DO "C:\Program Files (x86)\Notepad++\notepad++.exe" "%a"


回答2:

You might also want to write the batch file in this way:

set command=C:\Program Files (x86)\Notepad++\notepad++.exe
FOR /R d:\data %%a IN (*.dtd) DO %command% %%a


回答3:

If you do not want files from previous session to be opened then add the -nosession parameter.
(here example for dtd extension in a .bat file)

for /R %%x in (*.dtd) do (
    start "" "C:\Program Files\Notepad++\notepad++.exe" -nosession "%%x"
)