Dir command
dir command can be used to list the files from command prompt. This article explains the syntax for different usecases.
- A simple dir command without any other arguments lists all the files/subfolders that exist in the current folder.
- Lists the subfolders/files names in bare format.
Using wild cards with dir
Dir command accepts wild cards to display information only for the files that match the pattern specified. The below examples illustrate different use cases where we can use these wild cards
- List files of certain type or based on extension
For example to list all jpeg files in the current folder, we can run the below command.
To list all excel files
We can even specify multiple extension in dir command to list files of any of the types. To list all files created with Office applications like Word, Excel, Powerpoint etc we can run below command.
List file names based on type
dir command can list the file names and also the subfolders names. We can be selective and say that we want only names of the files to be listed or only the names of the subdirectories to be listed.
- List only directories
- List only files
Display files based on file attributes
We can filter out which files should be listed in the dir command output based on read-only, system, hidden archive file attributes.
- For example, to list read-only files in the current directory, the command is:
- Similarly to display hidden files
- For the opposite case of looking for files where an attribute is not set, we can append ‘-‘ to the attribute code. For example, to print the file names without archive attribute set, we can use the below command.
- Exclude Read-only files from the listing.
- Exclude hidden files from listing.
- Exclude system files from listing
Print metadata of files using dir command
- Find out who owns a file
How to get absolute path using command prompt ?
dir /s /b would print absolute path.
I want to list all the empty subdirectories in a folder and then delete them. How do I do that using dir command
Is it possible to get dir to print paths with spaces in a directory name?
Answered the question… Now the real problem: Have a command that gives “failed to load external entity” for a file inside a directory with a space. Here’s the command:
for /F %i in (‘dir /s /b D:\YourDirectory\filepath\Folio.xml’) do (C:\progra
1\xmlstarlet\xml.exe ed –inplace -d “//overlay[data/webViewUrl[contains(text(),’shopthis.mastercard’)]]” %i)
Your help is appreciated!
Is it possible to get the file icon with dir cmd?
I would like to list files and extract icon to show them in my application.
I would like to get the last modified time stamp of the latest file in the directory like just the date and time field values alone into different variables. Something similar to using awk, cut commands in Unix.
Special danish characters
I routinely use
dir /o /w > files.txt
to create a text file containing the file names in a folder. I can easily edit that file for use as a table of content for the audio newspaper hosted on our site. The file names are so long, that dir lists them in one column, which is perfect.
BUT: The files have danish special letters æ (html: æ) – ø (ø) – å (å) and their uppercase counterparts, Æ, Ø, Å. These come out wrong with the dir command, and have to be edited manually.
Q: Is there a way to make the dir command output these letters correctly? (Windows 7 Pro, Danish version, computer is NOT connected to the internet…)
you must launch/start/load the CMD tool like “cmd /U” then use again what you were trying
How do you list additional attributes to include not only the file name but also the date, type, and size of the file? Thank you.
Hello,
how can I create a text file list of the contents of a folder and hide the file extensions?
I already have my list of filenames in a file using “dir /b > Songs.xls”, but after every filename in the Songs.xls I still see the extention “.mp3” and I would like this to be removed from the filename.
THX in advance,
Dirkio
Thanks for the article
Is there any way to get a list of created date : modified date and access date in one output?
Get created time of a file
dir /TC
Find last accessed time of a file
dir /TA
Find last modified time of a file
dir /TW
What if I want to list the filenames from another folder?
When I type dir /e:-d /b , I get an error message that it cannot find e:
Same with dir e: /b and dir /e: /b .
Dir doesn’t seem to work with other folder designations.
I want to take the path from dir filename /s /p and use it to start the program from that path. Is it possible? And if yes could you tell me how.
I am using Windows 10.
I have chosen the 24 hour format HH:mm for time.
And indeed, when use file explorer to examine the contents of a folder, the times
of the files appear in this format.
But when I use the command prompt cmd
and then give the command dir
the times appear in the 12 hour format hh:mm followed by AM or PM.
What can I do so that when I give the dir command the times of the files
will be in the 24 hour format HH:mm
?
Thanks for your help.
How can I modify this command to create filelist.txt only if .pdf files are present
dir *.pdf /b /a:-d /o:n > filelist.txt
have a directory with the following files:
proc-0000.txt
proc-0001.txt
proc-0002.txt
proc-0003.txt
if i enter “dir *3.*” i get an unexpected return:
proc-0002.txt
proc-0003.txt
why?
if i had these files:
proc-000.txt
proc-001.txt
proc-002.txt
proc-003.txt
and enter ” dir *3.*” i only get (as expected):
proc-003.txt
what is going on with tht dir command?
dir /s no longer works correctly. If the directory doesn’t exist, dir /s now finds other directories near by and displays them, but doesn’t list them.
For instance:
dir /s \Scripts\PyScripts\work
shows:
Volume in drive T is WB10TB
Volume Serial Number is 8C30-2523
Directory of T:\Scripts\PyScripts\Keep_Old_Stuff\Scripts\Perl\Scripts\PerlProgs
10/19/2019 03:57 PM work
0 File(s) 0 bytes
Total Files Listed:
0 File(s) 0 bytes
1 Dir(s) 3,967,826,636,800 bytes free
Extract Web server content:
Web server admin needs to run this one command for each website to extract its structure:
Windows based web servers: dir /S /B /O *.* >> replace_with_Server_Name_website_name.txt
How to use this command
I think this was not yet addressed:
How would i include a specific file extension when i also specify a folder, e.g.
dir /b /s /a-d “C:\Users\peter\many LAZ and LAS files folder\” > “File List.txt”
Where would i put the *.LAZ expression, if i only want the LAZ files in this directory to be printed in the output list?
MS-DOS and Windows command line dir command
The dir command displays information about files and directories, and how much disk space is available. By default, it displays the name, size, and last modification time of every file in the current directory.
Availability
Dir is an internal command available in the command line of all Microsoft operating systems.
Description
The dir command displays a list of files and subdirectories in a directory. With the /S option, it recurses subdirectories and lists their contents as well.
Options listed below may be preset in the DIRCMD environment variable. To override preset options, prefix any switch with — (hyphen), for example, "/-W".
Syntax
The syntax of the dir command has evolved somewhat over time. Select your operating system to jump to the information that applies to your version.
Windows 11, 10, 8, 7, Vista, XP, and 2000 syntax
| [Drive:][Path][FileName] | Specifies the drive, directory, or files to list. Multiple filespecs are allowed, e.g., "*.txt *.exe". |
| /A:Attributes | Displays only files with the specified file attributes. Attributes is several letters, each representing an attribute as shown below. |
D : Directories.
R : Read-only files.
H : Hidden files.
A : Files marked ready for archiving.
S : System files.
I : Non-indexed files.
L : Reparse points.
— : Prefix meaning "not".
N : By name (alphabetic).
S : By size (smallest first).
E : By extension (alphabetic).
D : By date/time (oldest first).
G : Group directories first.
— : Prefix to reverse order.
C : Creation time.
A : Last access time.
W : Last write time.
Windows ME, 98, 95, 3.x, and MS-DOS syntax
| [Drive:][Path][FileName] | Specifies drive, directory, or files to list. Multiple filespecs are allowed, e.g., "*.txt *.exe". |
| /P | Pauses after each screenful of information. |
| /W | Uses wide list format. |
| /A[:Attributes] | List only files with the specified file attributes. Attributes is several letters indicating: |
Examples
Lists all files and directories in the current directory.
Lists any file whose name has the file extension ".exe".
Because of how the wildcard matching works, it's also shows files with a file extension with four or more characters (e.g., .exec).
List any files whose name has the file extension ".txt" or ".doc".
Lists only directories.
List only files with the read-only attribute.
Recursively lists files and directories in the directory, and in any subdirectories. For instance, if your current directory is the root directory "C:\>," this command lists every file and directory on the C: drive.
Pause after each screenful of output. Use this option if the information is scrolling past the screen before you can read it. You are prompted to press any key before listing continues past the current screen.
Lists multiple file names on every line, producing "wide" output, which displays more file names at once. However, other information such as file size is omitted.
Recursively lists all files and directories in the current directory and any subdirectories, in wide format, pausing after each screen of output.
Same as the above command, but lists everything in C:\Program Files, instead of the current directory. Because the directory name contains a space, it is enclosed in double-quotes, to prevent it from being interpreted is as two separate options.
Lists files and directories in the current directory in alphabetical order. This example is the same as only running dir because files and directories are listed in alphabetical order by default.
Lists files in reverse alphabetical order.
Lists any files and directories in C:\Windows, and any of its subdirectories (/s), which have both the "hidden" and "system" file attributes (/a:sh). Also, lists the owner of the file (/q), and pauses after each screen of output (/p).
The above command uses vertical bars to pipe the output from dir to the command find, and then to the command more. The result is a list of all files and directories in the root directory of the current drive (\), with extra information. Namely, find also displays the number of files in each directory, and the amount of space occupied by each.
Runs the dir command, but redirects the output to the file myfile.txt, instead of displaying it on the screen. Here, the dir command has no options, but redirection works with any command you specify, so the following command also works.
To view the file's contents, you can use the type command.
If the file is very long, you can pipe type to more, so it pauses after each screen.
Related information
report this ad
Dir Command
Примеры команд Dir, переключатели, опции и параметры Больше
Команда dir – это команда командной строки, используемая для отображения списка файлов и подпапок, содержащихся в папке.
Для каждого перечисленного файла или папки команда dir по умолчанию покажет дату и время последнего изменения элемента, если элемент является папкой (помеченной как ) или файлом, размер файл, если применимо, и, наконец, имя файла или папки, включая расширение файла.
Вне списка файлов и папок команда dir также отображает текущую букву диска раздела, метку тома, серийный номер тома, общее количество файлов в списке, общий размер этих файлов в байтах, количество перечисленных подпапок и общее количество байтов, оставшихся свободными на диске.
Наличие команды Dir
Команда dir доступна из командной строки во всех операционных системах Windows, включая Windows 10, Windows 8, Windows 7, Windows Vista и Windows XP.
Более старые версии Windows также включают команду dir, но с меньшим количеством параметров, чем мы перечислили ниже. Команда dir также является командой DOS, доступной во всех версиях MS-DOS.
Команду dir можно найти в автономных версиях командной строки, например, доступных в дополнительных параметрах запуска и параметрах восстановления системы. Команда dir также включена в консоль восстановления в Windows XP.
Доступность некоторых переключателей команд dir и другого синтаксиса команд dir может отличаться в разных операционных системах.
Синтаксис команды Dir
dir [ диск : ] [ путь ] [ имя файла ] [/a [[: ] атрибуты ]] [/b ] [/c ] [ /d ] [/l ] [/n ] [/o [[: ] сортировщик ]] [/p ] [/q ] [/r ] [/s ] [/t [[: ] время ]] [/w ] [ /x ] [/4 ]
См. Как читать синтаксис команды, если вы не уверены, как интерпретировать синтаксис команды dir, как я написал выше или как показано в таблице ниже.
При выполнении в одиночку этот переключатель отображает все типы файлов и папок, в том числе те, которые имеют атрибуты файлов, которые обычно не позволяют отображаться в командной строке или в Windows. Используйте /a с одним или несколькими из следующих атрибутов (двоеточие необязательно, пробелы не требуются), чтобы в результатах команды dir отображались только те типы файлов:
a = архивные файлы
h = скрытые файлы
i = не проиндексированные файлы содержимого
l = точки повторного анализа
r = файлы только для чтения
s = системные файлы
v = файлы целостности
x = нет файлов очистки
– = Используйте это как префикс к любому из вышеупомянутых атрибутов, чтобы исключить элементы с этими атрибутами файла из результатов.
Используйте эту опцию, чтобы указать порядок сортировки результатов. При выполнении в одиночку /o сначала перечисляет каталоги, а затем файлы в алфавитном порядке. Используйте эту опцию с одним или несколькими из следующих значений (двоеточие необязательно, пробелы не нужны), чтобы отсортировать результат команды dir указанным способом:
d = сортировка по дате/времени (сначала самая старая)
e = сортировка по расширению (по алфавиту)
g = сначала каталог группы, а затем файлы
n = сортировка по имени (в алфавитном порядке)
s = сортировка по размеру (сначала наименьшая)
– = Используйте это в качестве префикса с любым из указанных выше значений, чтобы изменить порядок (например, -d для сортировки по первому новому, -s для крупнейших сначала и т. д.).
Используйте эту опцию с одним из значений ниже (двоеточие необязательно, пробелы не требуются), чтобы указать поле времени, которое будет использоваться при сортировке и/или отображении результатов:
a = последний доступ
w = последний написанный
Учитывая объем информации, которую обычно возвращает команда dir, сохранение всей информации в текстовом файле с помощью оператора перенаправления обычно является разумной идеей. См. Как перенаправить вывод команды в файл для получения дополнительной информации о том, как это сделать.
Примеры команд Dir
В этом примере команда dir используется одна, без каких-либо спецификаций drive : , path, filename или каких-либо ключей, что приводит к получению результата, подобного этот:
Как вы можете видеть, команда dir была выполнена из корневого каталога C (то есть C: \>). Без указания, где именно перечислить содержимое папки и файла, команда dir по умолчанию отображает эту информацию, из которой она была выполнена.
В приведенном выше примере мы просим, чтобы команда dir показала результаты с диска : и пути из c: \ users , а не из того места, откуда я запускаю команду. Мы также указываем с помощью переключателя /a с атрибутом h , что мы хотели бы видеть только скрытые элементы, что приведет к чему-то вроде этого:
Небольшой список каталогов и один файл, который вы видите в приведенном выше результате, не составляют всю папку c: \ users – только скрытые файлы и папки. Чтобы просмотреть все файлы и папки, вместо этого вы должны выполнить dir c: \ users/a (удалив h ).
В этом чуть более сложном, но гораздо более практичном примере команды dir мы просим, чтобы на нашем жестком диске был выполнен поиск файлов CSV, а затем минимальные результаты выводятся в текстовый документ. Давайте посмотрим на этот кусок по частям:
- c: \ *. csv указывает команде dir просмотреть все файлы ( * ), заканчивающиеся расширением CSV ( .csv ), в корень диска c: .
- /s указывает dir идти глубже, чем корень c: и вместо этого искать файлы, подобные этому, в каждой папке, настолько же глубокой, насколько и папки.
- /b удаляет все, кроме пути и имени файла, по существу создавая читаемый «список» этих файлов.
- > – это оператор перенаправления, означающий «отправить куда-то».
- c: \ users \ tim \ desktop \ csvfiles.txt – это место назначения для перенаправителя > , то есть результаты будут записаны в csvfiles.txt вместо командной строки, который будет создан в расположении c: \ users \ tim \ desktop (т. е. на рабочем столе, который вы видите при входе в систему).
Когда вы перенаправляете вывод команды в файл, как мы делали здесь в этом примере команды dir, командная строка ничего не отображает. Тем не менее, вывод точный , который вы бы видели, вместо этого находится внутри этого текстового файла. Вот как выглядел мой csvfiles.txt после выполнения команды dir:
Хотя вы, конечно, могли бы пропустить перенаправление файлов и даже переключатель «пустой формат», с результатами было бы очень трудно работать в окне командной строки, что затрудняло бы получение того, что вы искали – местоположения каждого CSV-файла. файл на вашем компьютере.
Dir Связанные команды
Команда dir часто используется с командой del. После использования команды dir для поиска имени и местоположения файла (ов) в любой конкретной папке (папках) можно использовать команду del для удаления файлов непосредственно из командной строки.
Аналогичным является команда rmdir/s и более старая команда deltree , используемая для удаления папок и файлов. Команда rmdir (без параметра/s) полезна для удаления пустых папок, которые вы найдете с помощью команды dir.
Как упоминалось выше, команда dir также часто используется с оператором перенаправления.
Описание команды DIR
Команда DIR выводит список файлов и подкаталогов каталога. Вызванная без параметров команда dir выводит метку тома и серийный номер, за которыми следует список каталогов и файлов на диске, включая их имена, дату и время последнего изменения. А для для просмотра дерева каталогов используется команда TREE.
Для файлов dir выводит также расширение имени и размер в байтах. Команда dir также выводит общее число перечисленных файлов и каталогов, их общий размер и свободное пространство (в байтах) на диске.
Синтаксис и параметры команды DIR
dir [диск:][путь][имя_файла] [. ] [/p] [/q] [/w] [/d] [/a[[:]атрибуты]][/o[[:]порядок_сортировки]] [/t[[:]поле_сортировки]] [/s] [/b] [/l] [/n] [/x] [/c], где