How to search and find all the files with particular name using batch

batchbatch filecmd.exe

I am running a following command,

@echo off
cls
for /r D:\ %%a in (*) do if "%%~nxa"=="new.txt" set p=%%~dpnxa
if defined p (
echo File found its path - %p%
pause
) else (
echo File not found !
pause
)

it will search for the file named new.txt on whole drive D: folders and sub folders as a final result, it shows the full path of that file new.txt as an output like below, (lets assume new.txt file in D:\folder\ )

File found and its path - D:\folder\new.txt
Press any key to continue . . . 

But the problem is , if there is multiple file with same name new.txt in drive D: on different folder or sub folder , it only shows one path output.

My need is, want to show all files path with the same name new.txt on drive D: like below output,

Expected Output need like this,

Files found : 4
Files Paths : 
1 - D:\folder\new.txt
2 - D:\new folder\new.txt
3 - D:\files\new.txt
4 - D:\folder\new\new.txt

pls help..Thx in Advance.

Best Answer

I want to show all files path with the same name new.txt on drive D:

Expected Output:

Files found : 4
Files Paths : 
1 - D:\folder\new.txt
2 - D:\new folder\new.txt
3 - D:\files\new.txt
4 - D:\folder\new\new.txt

Use the following batch file:

@echo off
setlocal
rem change to the correct directory
cd /d d:\
rem count the files
dir /b new.txt /s 2> nul | find "" /v /c > %temp%\count
set /p _count=<%temp%\count
rem cleanup
del %temp%\count
rem output the number of files
echo Files found : %_count%
rem list the files
echo Files Paths :
dir /b new.txt /s
endlocal

  • An A-Z Index of the Windows CMD command line
  • A categorized list of Windows CMD commands
  • del - Delete one or more files.
  • dir - Display a list of files and subfolders.
  • endlocal - End localisation of environment changes in a batch file. Pass variables from one batch file to another.
  • find - Search for a text string in a file & display all the lines where it is found.
  • set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
  • setlocal - Set options to control the visibility of environment variables in a batch file.
Related Question