10

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.

AjV Jsy
  • 5,799
  • 4
  • 34
  • 30
user2387527
  • 101
  • 1
  • 1
  • 3

2 Answers2

6
@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
npocmaka
  • 55,367
  • 18
  • 148
  • 187
0

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?

Community
  • 1
  • 1
Kate
  • 1,556
  • 1
  • 16
  • 33