- Windows find directory command
- Syntax
- Parameters
- Remarks
- Examples
- How can I return to the previous directory in windows command prompt?
- 4 Answers 4
- md_autoruns.cmd:
- mycd.bat:
- aliases:
- How to find the mysql data directory from command line in windows
- 8 Answers 8
- How to do a simple file search in cmd
- 5 Answers 5
- Как использовать команду find для поиска в Windows
- Откройте окно командной строки с правами администратора
- Ключи и параметры для команды find
- Синтаксис для команды поиска
- Поиск отдельного документа для текстовой строки
- Поиск нескольких документов по одной и той же текстовой строке
- Подсчитать количество строк в файле
- Отправьте вывод другой команды в команду поиска
Windows find directory command
Searches for a string of text in a file or files, and displays lines of text that contain the specified string.
Syntax
Parameters
Parameter | Description |
---|---|
/v | Displays all lines that don’t contain the specified . |
/c | Counts the lines that contain the specified and displays the total. |
/n | Precedes each line with the file’s line number. |
/i | Specifies that the search is not case-sensitive. |
[/off[line]] | Doesn’t skip files that have the offline attribute set. |
Required. Specifies the group of characters (enclosed in quotation marks) that you want to search for. | |
[ :][ |
]
Remarks
If you don’t use /i, this command searches for exactly what you specify for string. For example, this command treats the characters a and A differently. If you use /i, however, the search becomes non-case-sensitive, and it treats a and A as the same character.
If the string you want to search for contains quotation marks, you must use double quotation marks for each quotation mark contained within the string (for example, «»This string contains quotation marks»»).
If you omit a file name, this command acts as a filter, taking input from the standard input source (usually the keyboard, a pipe (|), or a redirected file) and then displays any lines that contain string.
You can type parameters and command-line options for the find command in any order.
You can’t use wildcards (* and ?) in file names or extensions that you specify while using this command. To search for a string in a set of files that you specify with wildcards, you can use this command within a for command.
If you use /c and /v in the same command line, this command displays a count of the lines that don’t contain the specified string. If you specify /c and /n in the same command line, find ignores /n.
This command doesn’t recognize carriage returns. When you use this command to search for text in a file that includes carriage returns, you must limit the search string to text that can be found between carriage returns (that is, a string that is not likely to be interrupted by a carriage return). For example, this command doesn’t report a match for the string tax file if a carriage return occurs between the words tax and file.
Examples
To display all lines from pencil.ad that contain the string pencil sharpener, type:
To find the text, «The scientists labeled their paper for discussion only. It is not a final report.» in the report.doc file, type:
To search for a set of files, you can use the find command within the for command. To search the current directory for files that have the extension .bat and that contain the string PROMPT, type:
To search your hard disk to find and display the file names on drive C that contain the string CPU, use the pipe (|) to direct the output of the dir command to the find command as follows:
Because find searches are case-sensitive and dir produces uppercase output, you must either type the string CPU in uppercase letters or use the /i command-line option with find.
How can I return to the previous directory in windows command prompt?
I often want to return to the previous directory I was just in in cmd.exe, but windows does not have the «cd -» functionality of Unix. Also typing cd ../../.. is a lot of typing.
Is there a faster way to go up several directory levels?
And ideally return back afterwards?
4 Answers 4
On Windows CMD, I got used to using pushd and popd . Before changing directory I use pushd . to put the current directory on the stack, and then I use cd to move elsewhere. You can run pushd as often as you like, each time the specified directory goes on the stack. You can then CD to whatever directory, or directories , that you want. It does not matter how many times you run CD. When ready to return , I use popd to return to whatever directory is on top of the stack. This is suitable for simple use cases and is handy, as long as you remember to push a directory on the stack before using CD.
Run cmd.exe using the /k switch and a starting batch file that invokes doskey to use an enhanced versions of the cd command.
Here is a simple batch file to change directories to the first parameter (%1) passed in, and to remember the initial directory by calling pushd %1.
md_autoruns.cmd:
We will also need a small helper batch file to remember the directory changes and to ignore changes to the same directory:
mycd.bat:
And a small aliases file showing what to do to make it all work:
aliases:
Now you can go up a directory level by typing ..
Add another . for each level you want to go up.
When you want to go back, type cd — and you will be back where you started.
Aliases to jump to directories like wk or tools (shown above) swiftly take you from location to location, are easy to create, and can really help if you work in the command line frequently.
How to find the mysql data directory from command line in windows
In linux I could find the mysql installation directory with the command which mysql . But I could not find any in windows. I tried echo %path% and it resulted many paths along with path to mysql bin.
I wanted to find the mysql data directory from command line in windows for use in batch program. I would also like to find mysql data directory from linux command line. Is it possible? or how can we do that?
In my case, the mysql data directory is on the installation folder i.e. ..MYSQL\mysql server 5\data It might be installed on any drive however. I want to get it returned from the command line.
8 Answers 8
You can issue the following query from the command line:
Output (on Linux):
Output (on macOS Sierra):
Or if you want only the data dir use:
These commands work on Windows too, but you need to invert the single and double quotes.
Btw, when executing which mysql in Linux as you told, you’ll not get the installation directory on Linux. You’ll only get the binary path, which is /usr/bin on Linux, but you see the mysql installation is using multiple folders to store files.
If you need the value of datadir as output, and only that, without column headers etc, but you don’t have a GNU environment (awk|grep|sed . ) then use the following command line:
The command will select the value only from mysql’s internal information_schema database and disables the tabular output and column headers.
How to do a simple file search in cmd
I want to quickly search for a file given its name or part of its name, from the windows command line (not power shell). This is similar to opening explorer and using the search box at the top.
Note: dir can search based on a string template but it will not search in the subdirectories.
Note2: findstr can be used to search for a token inside files and has a recursivity flag; it’s funny that a more complex find can be easily discovered .
5 Answers 5
dir /s *foo* searches in current folder and sub folders.
It finds directories as well as files.
/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.
searches for all txt file in the directory tree. Before using it just change the directory to root using
you can also export the list to a text file using
and search within using
EDIT 1: Although this dir command works since the old dos days but Win7 added something new called Where
will search for exe & dll in the drive c:\Windows as suggested by @SPottuit you can also copy the output to the clipboard with
just wait for the prompt to return and don’t copy anything until then.
EDIT 2: 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
Как использовать команду find для поиска в Windows
В Windows есть некоторые встроенные возможности поиска, но они могут вам не понравиться. Cortana или стандартное поле поиска на панели задач и поле поиска в проводнике файлов в Windows 10 позволяют выполнять поиск по содержимому файлов, но они могут быть медленными, особенно поиск в проводнике.
Существует более быстрый способ поиска содержимого файлов на жестком диске с помощью командной строки. Команда find ищет текстовые строки в файлах и возвращает строки из файлов, в которых была найдена текстовая строка.
ПРИМЕЧАНИЕ. Команда find не подходит для больших файлов или большого количества файлов.
Сегодня мы рассмотрим, как использовать команду find, и приведем несколько примеров.
Откройте окно командной строки с правами администратора
Открытие окна командной строки от имени администратора не требуется. Тем не менее, это поможет вам избежать раздражающих диалоговых окон подтверждения. Просто будьте осторожны, какие команды вы запускаете от имени администратора в командной строке. Использование команды find в качестве администратора безопасно, поскольку она не изменяет и не удаляет файлы.
Введите cmd.exe в поле поиска на панели задач. Затем щелкните правой кнопкой мыши на пункт « Командная строка» и выберите « Запуск от имени администратора» во всплывающем меню.
Если появится диалоговое окно « Контроль учетных записей », нажмите « Да», чтобы продолжить.
ПРИМЕЧАНИЕ. Это диалоговое окно может не отображаться в зависимости от настроек контроля учетных записей. Мы не рекомендуем полностью отключать UAC.
Ключи и параметры для команды find
Большинство команд имеют дополнительные ключи, которые изменяют стандартное действие команды. Вы можете получить справку, чтобы увидеть все доступные ключи для команды find , набрав в строке следующую строку и нажав Enter:
Ключи могут быть строчными или прописными.
Для параметра «string» вы должны заключить строку в двойные кавычки, иначе команда find не будет работать и вернет ошибку.
Параметр имени диска [drive:] [path] может быть любым, от буквы диска до одного файла или нескольких файлов.
Синтаксис для команды поиска
Синтаксис команды — это особый способ организации команды, ее ключей и параметров. Ниже приведен общий синтаксис команды find.
Ключи могут быть в любом порядке, если они находятся перед параметром «string» . Скобки [] указывают, что ключ или параметр является необязательным.
Поиск отдельного документа для текстовой строки
Сначала мы покажем вам, как искать в одном документе все вхождения текстовой строки. Следующая команда ищет в файле example1.txt фразу «groovypost — is the best tech site».
find «groovypost — is the best tech site» «C:\Users\Lori\Documents\FindCommandExamples\example1.txt»
ПРИМЕЧАНИЕ. Если в какой-либо части пути или имени файла есть пробелы, вы должны заключать в кавычки весь путь, как мы делали в приведенной выше команде. Кавычки на самом деле не нужны в этом случае, но они точно не помешают.
Обратите внимание, что фраза не была найдена в приведенном выше примере (ничего не указано под путем к файлу), даже если она находится в файле. Это потому, что случай в «groovypost» не совпадает с тем, что было в файле, то есть «groovyPost». Добавьте ключ « /i » (ignore case) сразу после команды поиска (перед фразой), чтобы игнорировать регистр при поиске текстовой фразы.
find /i «groovypost — is the best tech site» «C:\Users\Lori\Documents\FindCommandExamples\example1.txt»
Теперь фраза найдена, и вся строка, содержащая фразу, выводится на экран под путем к файлу, в котором выполняется поиск.
Поиск нескольких документов по одной и той же текстовой строке
Теперь, когда вы можете искать один файл для текстовой строки, давайте искать несколько файлов для одной и той же строки.
Вы можете указать несколько файлов для поиска в команде поиска, указав путь к каждому файлу в кавычках через пробел.
find /i «groovypost» «C:\Users\Lori\Documents\FindCommandExamples\example1.txt» «C:\Users\Lori\Documents\FindCommandExamples\example2.txt»
Вы также можете искать все текстовые файлы в каталоге, используя подстановочный знак, который является звездочкой (*), как показано в следующей команде.
find /i «groovypost» «C:\Users\Lori\Documents\FindCommandExamples\*.txt»
Поисковый термин был найден в обоих документах, а предложения, в которых они были найдены, перечислены под полным путем к каждому файлу.
Подсчитать количество строк в файле
Если вы хотите узнать, сколько строк в файле, вы можете использовать комбинацию команд type и find . Команда type отображает содержимое одного или нескольких текстовых файлов.
Мы передали результаты команды type в команду find, используя вертикальную черту (|). Мы использовали ключ « /v » для отображения всех строк, НЕ содержащих строку «» , поэтому каждая строка с текстом будет подсчитана. Чтобы отобразить только количество строк в текстовом файле (не сами строки), мы используем ключ « /c ».
type C:\Users\Lori\Documents\FindCommandExamples\example1.txt | find «» /v /c
Отправьте вывод другой команды в команду поиска
Вы также можете выполнить поиск определенной строки во всех именах файлов в каталоге, отправив выходные данные команды dir в команду find .
Например, мы получили список каталогов C:\Users\Lori\Documents\FindCommandExamples и все подкаталоги в этом каталоге (ключ /s ). Мы также указали использовать пустой формат без информации о заголовке (ключей « /b ») и отобразили список в том же формате, что и формат широкого списка (ключ « /w »), но отсортированный по столбцу (« /d »).
Затем мы направляем (|) вывод команды dir в команду find, добавляя только «example» в качестве параметра. Мы не добавляли никаких ключей в команду поиска. Имена файлов для поиска берутся из вывода команды dir .
dir «C:\Users\Lori\Documents\FindCommandExamples» /s /b /d | find «example»
А вы предпочитаете использовать команду поиска или поле поиска в проводнике? Как вы использовали команду поиска? Поделитесь своими идеями и примерами с нами в комментариях ниже.
Присоединяйтесь к нам, в нашем уютном Телеграмм-канале , где вас ждут новости мира IT, подборки книг и много-много интересного!