user2387527
user2387527

Reputation: 101

How do I create a batch file to search for file(s) with certain extension within a folder?

Please help! I an new to creating batch files.

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

  1. Search for file(s) with a certain file extension (i.e. .docx) within a folder
  2. Output both filename(s) and extension to a text file (.txt)
  3. In the text file, I want to add an index before the file name

For example, "folder 1" has these three files : test1.docx, test2.docx, test3.xlsx The batch file will search for these three files that have extension with .docx, and then output to a text file (i.e. search_result.txt)

In the search_result.txt, it will have this format :

1 test1.docx
2 test2.docx

here is what I have so far which is doing #1 and #2 items 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 for the help.

Upvotes: 10

Views: 25535

Answers (2)

Kate
Kate

Reputation: 1576

Assuming the index is just an incrementing count of the number of matches, you could just use a variable and increment it with each iteration of the loop. You need to enable delayed expansion of variables for this to work, this prevents the variable being expended when the loop is first evaluated and the same expanded variable used for each iteration. You can then reference the variable using !counter! rather than %expanded%.

I think something like this should work but I haven't run it so you might need to tweak 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 out this answer for some more info on delayed expansion: How do I increment a DOS variable in a FOR /F loop?

Upvotes: 0

npocmaka
npocmaka

Reputation: 57322

@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

Upvotes: 6

Related Questions