- findstr
- Syntax
- Parameters
- Remarks
- Examples
- Утилиты find и findstr — поиск через командную строку
- Утилита find командная строка
- Утилита FINDSTR командная строка
- How to Use the Find Command to Search in Windows
- Open the Command Prompt Window with Administrative Privileges
- Switches and Parameters for the find Command
- Syntax for the find Command
- Search a Single Document for a Text String
- Search Multiple Documents for the Same Text String
- Count the Number of Lines in a File
- Send the Output of Another Command to the Find Command
findstr
Searches for patterns of text in files.
Syntax
Parameters
Parameter | Description |
---|---|
/b | Matches the text pattern if it is at the beginning of a line. |
/e | Matches the text pattern if it is at the end of a line. |
/l | Processes search strings literally. |
/r | Processes search strings as regular expressions. This is the default setting. |
/s | Searches the current directory and all subdirectories. |
/i | Ignores the case of the characters when searching for the string. |
/x | Prints lines that match exactly. |
/v | Prints only lines that don’t contain a match. |
/n | Prints the line number of each line that matches. |
/m | Prints only the file name if a file contains a match. |
/o | Prints character offset before each matching line. |
/p | Skips files with non-printable characters. |
/off[line] | Does not skip files that have the offline attribute set. |
/f: | Gets a file list from the specified file. |
/c: | Uses the specified text as a literal search string. |
/g: | Gets search strings from the specified file. |
/d: | Searches the specified list of directories. Each directory must be separated with a semicolon (;), for example dir1;dir2;dir3 . |
/a: | Specifies color attributes with two hexadecimal digits. Type color /? for additional information. |
Specifies the text to search for in filename. Required. | |
[\ :][ |
] [. ]
Remarks
All findstr command-line options must precede strings and filename in the command string.
Regular expressions use both literal characters and meta-characters to find patterns of text, rather than exact strings of characters.
A literal character is a character that doesn’t have a special meaning in the regular-expression syntax; instead, it matches an occurrence of that character. For example, letters and numbers are literal characters.
A meta-character is a symbol with special meaning (an operator or delimiter) in the regular-expression syntax.
The accepted meta-characters are:
Meta-character | Value |
---|---|
. | Wildcard — Any character |
* | Repeat — Zero or more occurrences of the previous character or class. |
^ | Beginning line position — Beginning of the line. |
$ | Ending line position — End of the line. |
[class] | Character class — Any one character in a set. |
[^class] | Inverse class — Any one character not in a set. |
[x-y] | Range — Any characters within the specified range. |
\x | Escape — Literal use of a meta-character. |
\ | Beginning word position — Beginning of the word. |
string\> | Ending word position — End of the word. |
The special characters in regular expression syntax have the most power when you use them together. For example, use the combination of the wildcard character ( . ) and repeat ( * ) character to match any string of characters: .*
Use the following expression as part of a larger expression to match any string beginning with b and ending with ing: b.*ing
To search for multiple strings in a set of files, you must create a text file that contains each search criterion on a separate line.
Use spaces to separate multiple search strings unless the argument is prefixed with /c.
Examples
To search for hello or there in file x.y, type:
To search for hello there in file x.y, type:
To find all occurrences of the word Windows (with an initial capital letter W) in the file proposal.txt, type:
To search every file in the current directory and all subdirectories that contained the word Windows, regardless of the letter case, type:
To find all occurrences of lines that begin with FOR and are preceded by zero or more spaces (as in a computer program loop), and to display the line number where each occurrence is found, type:
To list the exact files that you want to search in a text file, use the search criteria in the file stringlist.txt, to search the files listed in filelist.txt, and then to store the results in the file results.out, type:
To list every file containing the word computer within the current directory and all subdirectories, regardless of case, type:
To list every file containing the word computer and any other words that begin with comp, (such as compliment and compete), type:
Утилиты find и findstr — поиск через командную строку
В этой статье мы с вами рассмотрим утилиту findstr и find командной строки, которые позволяет производить поиск строк в текстовом документе. Поиск через командную строку можно также настроить, используя шаблоны, которые настраиваются на основе регулярных выражений, но сперва, немного лирики…
В былые времена, когда я был еще полным чайником в компьютерах, мне пришлось услышать про волшебные “виртуальные диски”. В то время размер моего винчестера составлял 2 гигабайта, и на счету был каждый байт, я каждую картинки сжимал для экономии места, зато в системе был один фильм и одна игра “Age Of Empires 2”, я ее уже раз сто проходил. Так вот, я почему то решил, что “виртуальный диск”, это дополнительная память, которая может появится из воздуха… Где то два дня пытался всячески установить через Диспетчер устройств еще один винт на 500 метров, при том, что такого оборудования в системном блоке и подавно не было…
Утилита find командная строка
FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] «искомые_значения» [[диск:][путь]имя_файла[ . ]]
И так, смотрим на описание ключей:
[/V] – произвести вывод всех строк, которые НЕ содержат заданной.
[/C] – выводится только общее число строк, содержащих заданную.
[/N] – Вывод номеров отображаемых строк.
[/I] – Поиск без учета регистра символов.
[/OFF[LINE]] – Не пропускать файлы с установленным атрибутом «Автономный».
«искомые_значения» – собственно, строчка, поиск которой производится из командной строки Windows
[[диск:][путь]имя_файла[ . ]] – тут мы прописываем один или несколько имен документов, в которых нужно произвести поиск через командную строку, можно использовать подстановочные знаки.
Хорошо, теперь давайте попробуем написать несколько примеров.
Создадим на диске D:\ папку TEST, в который благополучно поместим три файла с расширениями .pdf, .txt и .mf. Для начала попробуем найти слово «const» во всех документах с расширением txt:
FIND «const» D:\TEST\*.txt
На выходе мы получим следующую информацию:
———- D:TESTSEND_MAIL_DATA.VBS.TXT
соnst toMSg =»to@yandex.ru» ‘получатель
соnst fromMSg =»from@gmail.com» ‘отправитель
соnst subjMsg = «Администратор» ‘субъект
соnst sndUsr =» login» ‘логин
соnst sndPswd =»password» ‘пароль
cоnst smtpSrvr = «smtp.gmail.com» ‘почтовый сервер
———- D:TESTSEND_MAIL_TEXT.VBS.TXT
cоnst toMSg =»to@yandex.ru»
cоnst fromMSg =»from@gmail.com»
cоnst subjMsg = «Администратор»
cоnst sndUsr =» login»
сonst sndPswd =»password»
сonst smtpSrvr = «smtp.gmail.com»
Как видим, мы получили список всех тех строчек, где встречается искомое слово.
Теперь попробуем сделать поиск через командную строку слова “samsung” во всех pdf файлах:
FIND «samsung» D:\TEST\*.pdf
Слово «samsung» встречается в одном документе, но, утилита FІND найти его не смогла, стоит обратить внимание, что и стандартный поиск операционной системы Windows также ничего не нашел, видимо, Google в этом все же больше преуспел.
Теперь попробуем усложнить задачу. Дело в том, что Windows ищет фразу не только в контексте файла, но и в его свойствах. Посмотрим, будет ли утилита find командной строки Windows производить поиск из описания. Я специально, по одному из каждого типа файлов (.pdf, .txt и .mf) вставлю в описание фразу «Victoria Sanremo». И так, приступим:
FIND «Victoria Sanremo» D:\TEST\*.*
В результат выполнения команды find, командная строка ничего не нашла в свойствах документов. Кроме утилиты FІND, есть еще и CMD FINDSTR, которая обладает немного большими возможностями.
Утилита FINDSTR командная строка
Утилита CMD FINDSTR предоставляется возможность осуществить поиск текста через командную строку не только в одном файле, или группе документов заданных по шаблону, но и с возможностью загрузки готового списка. И так, прежде всего, давайте посмотрим на основной синтаксис.
FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:файл][/C:строчка] [/G:файл] [/D:список_папок] [/A:цвета] [/OFF[LINE]] «искомые_значения»[[диск:][путь]имя_файла[ . ]]
/B – Данный ключ определяет поиск образца лишь в началах строчек.
/E — Данный ключ определяет поиск образца лишь в конце.
/R – Фразы и слова будут приниматься как регулярные выражения.
/S – Производит поиск файлов через командную строку в текущем каталоге и всех его подпапках.
/I – Данный ключ определяет, что поиск фразы из командной строки будет вестись без учета регистра.
/X – Производит вывод только тех строчек, которые содержат точное совпадение.
/V — Производит вывод только тех строчек, которые не содержат точного совпадения с искомой фразой.
/N — Производит вывод номера строчки (которые содержат точное совпадение) и ее содержимое.
/M — Производит вывод лишь имени документа, который содержит совпадение.
/O – Вывести список найденных строк через пустую строчку.
/P – Данный параметр определяет, что произойдет пропуск всех строк, которые содержат непечатаемые символы.
/OFF[LINE] — Не пропускает те документы, у которых установлен атрибут «Автономный».
/A:цвета – Шестнадцатеричный код цвета, для получения справки можете ввести команду «COLOR /?»
/F:файл – Производит чтение списка файлов из заданного документа.
/C:строчка – Использовать значение данного параметра как искомую фразу поиска.
/G:файл – Позволяет получить список строк из заданного документа.
/D:список_папок – Тут через точку с запятой мы можем задать список каталогов, в которых нужно произвести поиск через командную строку.
“искомые_значения” – Собственно, то, что мы ищем.
[диск:][путь]имя_файла — Задаем путь к документу (документам)
Что бы разделить между собой искомые фразы, между ними вставляется пробел, если параметр не содержит префикса /C. Например,
FINDSTR «Привет мир» data.txt
ищет «Привет» или «мир» в файле data.txt, а команда
FINDSTR /C:»Привет мир» data.txt
ищет фразу «Привет мир» в файле data.txt.
Регулярные выражения являются своеобразным бонусом, которым не то, что оболочка, но и язык программирования не всегда может похвастаться. При поиске из командной строки, регулярные выражения позволяют задавать собственные шаблоны (для справки по некоторым значениям введите в cmd findstr/? ), они также используются в сценариях сервера Windows Script Host, за это отвечает отдельный объект.
Спасибо за внимание. Автор блога Владимир Баталий
How to Use the Find Command to Search in Windows
Windows has some built-in search capabilities, but they may not be to your liking. Cortana or the standard Search box on the Taskbar and the Search box in File Explorer in Windows 10 allow you to search through file contents, but they can be slow, especially the File Explorer search.
There’s a faster way to search the contents of files on your hard drive using the command line. The find command searches for text strings in files and returns the lines of text from the files in which the text string was found.
NOTE: The find command is not suitable for large files or large numbers of files.
Today we’ll cover how to use the find command and we’ll provide some examples.
Open the Command Prompt Window with Administrative Privileges
Opening the Command Prompt window as administrator is not necessary. However, it does help you avoid annoying confirmation dialog boxes. Just be careful what commands you run as administrator on the command line. Using the find command as administrator is safe as it doesn’t change or delete any files.
Enter cmd.exe in the Search box on the Taskbar. Then, right-click on the Command Prompt item under Best match and select Run as administrator from the popup menu.
If the User Account Control dialog box displays, click Yes to continue.
NOTE: You may not see this dialog box, depending on your User Account Control settings. We don’t recommend disabling UAC entirely.
Switches and Parameters for the find Command
Most commands have optional switches that modify the default operation of the command. You can get help to see all the available switches for the find command by typing the following line at the prompt and pressing Enter.
The switches can be lowercase or uppercase.
For the “string” parameter, you must surround the string with double quotes, otherwise the find command will not work and will return an error.
The [drive:][path]filename parameter can be anything from a drive letter to a single file or multiple files.
Syntax for the find Command
A command’s syntax is a specific way to organize the command and its switches and parameters. The following is the general syntax for the find command.
The switches can be in any order as long as they’re before the “string” parameter. The brackets [] indicate that the switch or parameter is optional.
Search a Single Document for a Text String
First, we’ll show you how to search one document for all occurrences of a text string. The following command searches the example1.txt file for the phrase “groovypost is the best tech site”.
NOTE: If there are spaces in any part of the path or file name, you must put quotes around the entire path, like we did in the above command. The quotes are not really needed in this case, but it doesn’t hurt to have them.
Notice that the phrase was not found in the above example (nothing is listed below the path to the file), even though it is in the file. That’s because the case in “groovypost” did not match what was in the file, which is “groovyPost”. Add the “/i” (lowercase or uppercase letter “i”) switch right after the find command (before the phrase) to ignore the case when looking for the text phrase.
Now, the phrase was found and the entire line containing the phrase prints to the screen below the path to the file being searched.
Search Multiple Documents for the Same Text String
Now that you can search one file for a text string, let’s search multiple files for the same text string.
You can specify multiple files to search in the find command by putting the path to each file in quotes separated by a space.
You could also search all text files in a directory using the wildcard character, which is an asterisk (*), as shown in following command.
The search term was found in both documents and the sentences in which they were found are listed under the full path to each file.
Count the Number of Lines in a File
If you want to know how many lines there are in a file, you can use a combination of the type and find commands. The type command displays the contents of one or more text files.
We piped the results of the type command into the find command using the vertical bar (|). We used the “/v” switch to display all lines NOT containing the “” string, so every line with text will be counted. To display only the number of lines in the text file (not the lines themselves), we use the “/c” switch.
Send the Output of Another Command to the Find Command
You can also search all file names in a directory for a certain string by piping the output of the dir command to the find command.
For example, we got the directory listing of the C:\Users\Lori\Documents\FindCommandExamples directory and any subdirectories in that directory (“/s” switch). We also specified to use the bare format with no heading information or summary (“/b” switch) and to display the listing in the same format as the wide list format (“/w” switch) but sorted by column (“/d” switch).
Then, we pipe (|) the output of the dir command into the find command, only adding “example” as the parameter. We didn’t add any switches to the find command. The file names to search come from the output of the dir command.
Do you prefer using the find command or the Search box in File Explorer? How have you used the find command? Share your ideas and examples with us in the comments below.