up vote 2 down vote favorite
share [g+] share [fb]

I want to print a numbered list of the file names in a directory.

I tried

dir /w > test.txt

What are the commands to do this?

link|improve this question

69% accept rate
feedback

2 Answers

up vote 2 down vote accepted
@echo off
setlocal enabledelayedexpansion
    set num=0
    FOR %%F IN (*) DO (
        set /a num += 1
        echo !num! %%~fF
    )
    echo %num% files
endlocal

"%%~fF" prints the full path. To print the short filename, use "%%F". See for /? near the end for all possible expansions.

Edit: to pass in a directory, change it to

FOR %%F IN (%**) DO (

And call it with a directory name with a following slash ("C:\Windows\", not "C:\Windows"), or with no directory name.

You could also change to the directory with pushd %* before the for loop, and then popd any time after the for loop. This would be useful if you needed to do more than enumerate the files, but you want to return to the original working directory.

Edit: Here's a more complete, annotated version. It also lists directories -- I missed that for doesn't do that by default:

@echo off
setlocal enabledelayedexpansion

    :: change to a dir
    pushd %*

    :: file counter
    set num=0

    :: dirs only
    FOR /D %%D IN (*) DO (
        set /a num += 1
        echo !num! %%D
    )

    :: files only
    FOR %%F IN (*) DO (
        set /a num += 1
        echo !num! %%F
    )

    :: final tally
    echo.
    echo %num% files

    :: return to original directory
    popd

endlocal

Simply save to a file with the extension .cmd, and put it somewhere in your path (eg, C:\Windows), and this should work on any recent Windows OS (tested on XP).

link|improve this answer
With the batch file , Is it possible that i can pass command line argument. E,g i make file newfile.bat and if i execute like this way newfile.bat---- path/of/dir ---- path/of/textfile – Mirage Jan 21 '10 at 2:46
THANKS FOR THAT , I will try – Mirage Jan 21 '10 at 3:03
feedback

If using Windows with NTFS, I think this could be done with the Everything search engine. It can search for file types, with particular elements in the file name, supports regular expressions, and can export to .txt.

alt text

link|improve this answer
this is a "list of files that use numbers for names", not a "numbered list of files". – quack quixote Jan 21 '10 at 16:05
~quack, yes, I misunderstood the last part of the question before it was revised. It was a bit ambiguous. – outsideblasts Jan 22 '10 at 22:08
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.