Cmd как найти файл по названию

Please try the following commands

List all files in the current directory & subdirectories

dir /b/s *.txt  

The above command searches for all txt file in the directory tree.

But as windows is started naming directories as .nuget,.vscode it also comes with the command above.

In order to avoid this and have a clean list use /a:-d filter as

dir /a:-d /b/s

Before using it just change the directory to root using

cd/

There is one more hacky command to do the same

for /r %f in (*) do @echo %f

Note: If you miss the @echo part in the command above it will try to execute all the files in the directories, and the /r is what making it recursive to look deep down to subdirectories.


Export result to text file

you can also export the list to a text file using

dir /b/s *.exe >> filelist.txt

and search within using

type filelist.txt | find /n "filename"

If you are looking for files with special attributes, you can try

List all Hidden Files

dir /a:h-d /b/s

List all System Files

dir /a:s-d /b/s

List all ReadOnly Files

dir /a:r-d /b/s

List all Non Indexed Files

dir /a:i-d /b/s

If you remove the -d from all commands above it will list directories too.


Using where in windows7+:

Although this dir command works since the old dos days but Win7 added something new called Where

where /r c:Windows *.exe *.dll

will search for exe & dll in the drive c:Windows as suggested by @SPottuit you can also copy the output to the clipboard with

where /r c:Windows *.exe |clip

just wait for the prompt to return and don’t copy anything until then.

Page break with more

If you are searching recursively and the output is big you can always use more to enable paging, it will show -- More -- at the bottom and will scroll to the next page once you press SPACE or moves line by line on pressing ENTER

where /r c:Windows *.exe |more

For more help try

where/?

Как быстро найти файл в Windows с помощью cmd ?

Приветствую вас, сейчас мы научимся, как найти файл или папку в Windows без помощи неважно работающего проводника системы, и будем использовать для этого либо команды в MS-DOS, либо с помощью его эмулятора – консоли команд cmd. У такого способа есть лишь один недостаток, который связан лишь с беспричинной боязнью пользователей перед текстовым интерфейсом работы с системой и сложившейся привычкой к графическому. Однако, по сути в обоих случаях нам всё равно приходится вручную набирать условия поиска потерявшегося файла или пакета файлов, а здесь без «вседозволенности» консоли просто не обойтись. От команд давно почившей операционной системы MS-DOS не скроется ничего, и cmd способна без труда открыть путь ко всем документам и директориям, которые находятся в чреве Windows .

Что нужно, чтобы найти файл в Windows ?

Нам нужно имя файла и программу, которая его создала либо умеет читать.

Итак, если уверены, что файл просто «потерялся», вам нужно через консоль оказаться в корневой папке системы. Для этого введём пару символов:

cd

корневая папка windows

и вы там. Если вы точно знаете имя файла или документа, это не проблема даже для поисковика Windows. Но есть ведь задача и посложнее…

А теперь, представьте, что вам нужно найти файл или документ, имя которого вы и толком-то не помните. Допустим, в названии что-то было про «установку». То-ли «установкА», то-ли «установкИ», то-ли «установОК»… Не проблема – так Windows и спросите:

dir *установ*.* /s

где

  • dir – команда отобразить список файлов и директорий
  • * — что-то там… (ну забыл я, мол)
  • . – расширение файла (текстовый, музыка, PDF-ка, фильм и т.п.)
  • /s – команда на поиск в текущей директории и подкаталогах.

как найти файл в Windows

Результаты через пару мгновений будут выглядеть примерно так:

результаты поиска

На этот же манер можно найти файл, если вы знаете, какое расширение он имеет, т.е. какой программой открывается. Командой

dir *.xls /s

или

dir *.docx /s

можно будет найти документы Exel и Word. Присмотритесь к примерам разновидностей команд (вариаций здесь множество):

dir *.txt *.doc

отобразит в одной выдаче документы с расширениями .doc и .txt

dir /p

команда с этим атрибутом (в отличие от /s) поможет. если результатов будет множество, а вам удобнее просматривать их с небольшим интервалом.

dir /on

выдаст список файлов и директорий в алфавитном порядке

dir  /s |find "i" |more

отображает все папки и их содержимое, включая время создания, количество файлов в каждой, сколько места занимают.

Успехов

I want a command to search for a file in a directory and all sub directories in windows using the command line. I saw all the available commands but I couldn’t find any suitable command to do this operation.

fixer1234's user avatar

fixer1234

27k61 gold badges72 silver badges116 bronze badges

asked Aug 18, 2010 at 6:52

Wael Dalloul's user avatar

At prompt (Command Line) type:

dir /S /P "PathFileName"

If you want to save the results in a text file:

dir /S "PathFileName" > "PathResultFilename"

Chaminda Bandara's user avatar

answered Aug 18, 2010 at 7:14

Matan Eldan's user avatar

Matan EldanMatan Eldan

2,6671 gold badge21 silver badges22 bronze badges

3

use the /b switch to dir to print full path might be helpful.
say, C: > dir /b /s *file*.*

still, you can filter the result with find or for, and redirect output to file with >filename

answered Aug 18, 2010 at 7:30

Jokester's user avatar

JokesterJokester

1,6633 gold badges14 silver badges21 bronze badges

dir was not meant for searching files but to list directories, but now there is where which can be used to search multiple file types as
where /R c:Users *.dll *.exe *.jpg

do check the full syntax and the answer for How to do a simple file search in cmd

WHERE [/R dir] [/Q] [/F] [/T] pattern...

Description:
    Displays the location of files that match the search pattern.
    By default, the search is done along the current directory and
    in the paths specified by the PATH environment variable.

Parameter List:
    /R       Recursively searches and displays the files that match the
             given pattern starting from the specified directory.

    /Q       Returns only the exit code, without displaying the list
             of matched files. (Quiet mode)

    /F       Displays the matched filename in double quotes.

    /T       Displays the file size, last modified date and time for all
             matched files.

    pattern  Specifies the search pattern for the files to match.
             Wildcards * and ? can be used in the pattern. The
             "$env:pattern" and "path:pattern" formats can also be
             specified, where "env" is an environment variable and
             the search is done in the specified paths of the "env"
             environment variable. These formats should not be used
             with /R. The search is also done by appending the
             extensions of the PATHEXT variable to the pattern.

     /?      Displays this help message.

  NOTE: The tool returns an error level of 0 if the search is
        successful, of 1 if the search is unsuccessful and
        of 2 for failures or errors.

Examples:
    WHERE /?
    WHERE myfilename1 myfile????.*
    WHERE $windir:*.* 
    WHERE /R c:windows *.exe *.dll *.bat  
    WHERE /Q ??.??? 
    WHERE "c:windows;c:windowssystem32:*.dll"
    WHERE /F /T *.dll 

answered Dec 24, 2017 at 21:57

Vinod Srivastav's user avatar

Searching for a file in Windows is not an easy job if your files are not organized and one of the ways to search your files using tags keywords in the Windows Search box inside File Explorer. However, Windows File Explorer search results are not that accurate and it takes a longer time but why wait if you can search files much faster using Windows 10 Command Prompt.  

Finding Files Using Windows 10 Command Prompt. 

You can search files on your hard drive faster using Windows Command Prompt.

Step 1: Press Start and type CMD, then press Enter to launch the Command Prompt. After successfully launching the Command Prompt, type the below command, and press Enter to pull up a list of files and folders. 

dir

Step 2: For moving down into a particular directory, use the below command followed by a folder name,  until you reach the folder you want to search.

cd folder_name

Step 3: Now type dir command again but this time with your search term, follow dir with your search term in quotes with an asterisk term before closing the quotes (For example, type dir “Raveling*”) and press Enter. The command prompt will show you the file location along with the list of files name starting with a similar keyword. 

The asterisk is what’s known as a wildcard and, in our example, it stands for anything that follows the word ‘highlands’, such as ‘raveling.doc’, ‘raveling.xls’ or My Business plans.txt’.

If you don’t know the exact location of your file in your hard drive, then instead of manually navigating through your directories, start searching from the very top level of your hard drive and include every sub-folder.

Step 4: The top level of the drive is represented by a backslash and, to include subdirectories, you add a forward slash and ‘s’ to the end of the query as shown below:

 dir “Raveling*” /s 

The above command is my all-time favorite because, with the help of this command, I don’t have to force my brain to remember the location of the files. This trick usually takes seconds to search the entire drive for the file.  

You can also search for a particular file type by using a command dir *.pdf /s and it will show you all files saved with the .pdf extension. You can try this for other files too (for example: .doxc, .png, .exe and more).

Note: The position asterisk symbol in the command matter a lot so type carefully and check once before executing the command.

How all these commands work.

Now you know enough to find any file on your entire hard drive within few seconds but if you are more curious to know how all these commands are working and what all these symbols stand for, then continue reading this post.

Let’s discuss each term one by one:

  • dir command is for showing files on the current directory, but it can also show files from anywhere in the drive of the system.
  • / tells dir to search from the top-level or root directory of the hard drive.
  • /s is used for searching sub-directories.
  • * asterisk is using before text (for example *.pdf) show all files ending with .pdf and * using at the end (for example raveling*) show you all file-names starting with that word.

So, this is all that you need to know for searching any file quickly within a few seconds using Windows 10 Command Prompt. 

Last Updated :
12 Mar, 2021

Like Article

Save Article

Приветствую, уважаемые участники проекта Habrahabr. Сегодня я хочу рассказать вам как выполнить поиск файлов в интерпретаторе командной строки Windows — cmd.exe. Я не буду вам писать такую команду, как dir или find. Мы сегодня рассмотрим другой, более лучший способ.

Давайте представим такую ситуацию: «Вы начинающий программист, и вам стоит задача: Сделать импорт всех (или некоторых файлов) из определенного каталога. Причем, чтобы можно было искать любые файлы, с любым названием и расширением. При этом импорт должен быть помещен в один файл. С сохранением всех путей файлов, построчно».

Вот как будет выглядеть данный код:

@Echo Off & Title Seacher File
Echo Status oparations: In Progress...
For /R D: %%i In (*.doc) Do (
 	If Exist %%i (
		Echo %%i >> D:Resault.doc
	)
)
Cls & Echo Status Oparations: Ended Seacher
Pause & Start D:Resault.doc & Echo On

А теперь, давайте разберем, что он делает!

Первая строка кода:

@Echo Off & Title Seacher File

Скрывает все происходящее в командном файле, и параллельно меняет заголовок командной строки.

Вторая строка кода:

Echo Status oparations: In Progress...

Выводит статус операции.

Третья строка кода:

For /R D: %%i In (*.doc) Do (

Иницилизация цикла For.

Четвертая строка кода:

If Exist %%i (

Иницилизация цикла If.

Пятая строка кода:

Echo %%i >> D:Resault.doc

Условие если файл найден.

Восьмая строка кода:

Cls & Echo Status Oparations: Ended Seacher

Очистка крана, и вывод конечного сообщения об окончании операции.

Девятая строка кода:

Pause & Start D:Resault.doc & Echo On

Пауза, перед закрытием пакетного файла и запуск файла с результатами.

Выводы

Данный bat файл, универсален, удобен в использовании, но есть одно, НО!

Условия поиска нужно вводить вручную, и путь где искать

Понравилась статья? Поделить с друзьями:
  • Как найти протокол дпс
  • Как составить выкройку для вязания жилета
  • Как найти группу ватсап где меня нет
  • Как найти строку 1400
  • Видеоурок как составить план текста 4 класс