Suppose: I want to list the complete paths of all text files named test.txt under drive E. I used the following code:
If there happens to be a folder named test.txt under the root directory of drive E, then there will be a ruckus: the path E:\test.txt will be displayed as many times as there are files under E:\test.txt! If there are no files under E:\test.txt, the path E:\test.txt will not be displayed at all. If the folder test.txt exists in a subfolder of drive E, such a situation will not occur.
A little analysis reveals that the reason is this: the name test.txt is ambiguous: it can represent both a text file named test and a folder named test.txt; and the dir command for searching for a specified file in the entire partition must be written in the format dir /a-d /s e:\test.txt. In this way, because of the ambiguity of test.txt, dir will search for all types of files under the folder e:\test.txt and also search for all text files named test under drive E.
The solution is: check the result after dir. The code can be modified as:
[ Last edited by namejm on 2007-3-8 at 03:52 PM ]
@echo off
for /f "delims=" %%i in ('dir /a-d /b /s e:\test.txt') do echo "%%~dpi"
pause
If there happens to be a folder named test.txt under the root directory of drive E, then there will be a ruckus: the path E:\test.txt will be displayed as many times as there are files under E:\test.txt! If there are no files under E:\test.txt, the path E:\test.txt will not be displayed at all. If the folder test.txt exists in a subfolder of drive E, such a situation will not occur.
A little analysis reveals that the reason is this: the name test.txt is ambiguous: it can represent both a text file named test and a folder named test.txt; and the dir command for searching for a specified file in the entire partition must be written in the format dir /a-d /s e:\test.txt. In this way, because of the ambiguity of test.txt, dir will search for all types of files under the folder e:\test.txt and also search for all text files named test under drive E.
The solution is: check the result after dir. The code can be modified as:
@echo off
for /f "delims=" %%i in ('dir /a-d /b /s e:\test.txt') do (
if /i "%%~nxi"=="test.txt" echo "%%~dpi"
)
pause
[ Last edited by namejm on 2007-3-8 at 03:52 PM ]
Recent Ratings for This Post
( 6 in total)
Click for details
尺有所短,寸有所长,学好CMD没商量。
考虑问题复杂化,解决问题简洁化。
考虑问题复杂化,解决问题简洁化。
