How to create a batch file to search for files with a specific extension in a folder?

Please, help! I am new to creating batch files.

I am trying to create a batch file to do the following:

  • Search for files (files) with a specific file extension (e.g. .docx) in a folder
  • Output both the file name and the extension to a text file (.txt)
  • In a text file I want to add an index before the file name

For example, in "folder 1" there are three files: test1.docx, test2.docx, test3.xlsx The batch file will search for these three files with the extension .docx and then output them to a text file (i.e. Search_result.txt )

In the file search_result.txt it will have the following format:

1 test1.docx
2 test2.docx

this is what i still do # 1 and # 2 mentioned above but i need help to implement # 3.

@echo off for /r %%i in (*.docx) do echo %%~nxi >> search_result.txt 

Thank you in advance.

+8
batch-file
source share
2 answers
 @echo off setlocal enabledelayedexpansion set /a counter=1 for /r %%i in (*.docx) do ( echo !counter! %%~nxi >> search_result.txt set /a counter=!counter!+1 ) endlocal 
+4
source share

Assuming the index is just an increasing number of matches, you can simply use the variable and increment it with each iteration of the loop. You need to enable slow expansion of variables in order for this to work, this prevents the variable from being consumed when the loop is first computed, and the same extended variable used for each iteration. You can then reference the variable using! Counter! not% advanced%.

I think something like this should work, but I did not run it, so you may need to configure it:

 @echo off setlocal ENABLEDELAYEDEXPANSION set /a counter=1 for /r %%i in (*.docx) do ( echo !counter! %%~nxi >> search_result.txt set /a counter=!counter!+1 ) endlocal 

Check this answer for more information on delayed extensions: How do I increase the value of a DOS variable in a FOR / F loop?

0
source share

All Articles