Home » Questions » Computers [ Ask a new question ]

What are the commands to display a numbered list of the files in a directory?

What are the commands to display a numbered list of the files in a directory?

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

Asked by: Guest | Views: 434
Total answers/comments: 2
Guest [Entry]

"@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)."
Guest [Entry]

"You can do a small hack for this:
@echo off
dir /b >test.txt
find /n /v """" <test.txt
del /f /q test.txt

It will show like:
[1]file1.txt
[2]file2.txt

and so on."