- поиск find
- Синтаксис Syntax
- Параметры Parameters
- Комментарии Remarks
- Примеры Examples
- 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
- Find windows OS version from command line
- Find OS Version and Service Pack number from CMD
- Check Windows version using WMIC command
поиск find
Выполняет поиск строки текста в файле или файлах и отображает строки текста, содержащие указанную строку. 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 /v | Отображает все строки, не содержащие указанный объект . Displays all lines that don’t contain the specified . |
/C /c | Подсчитывает количество строк, содержащих указанный объект , и отображает итоговое значение. Counts the lines that contain the specified and displays the total. |
/n /n | Предшествует каждой строке с номером строки файла. Precedes each line with the file’s line number. |
/i /i | Указывает, что при поиске регистр не учитывается. Specifies that the search is not case-sensitive. |
[«/OFF» [строка]] [/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
Если вы не используете /i, эта команда ищет именно то, что указано для String. If you don’t use /i, this command searches for exactly what you specify for string. Например, эта команда обрабатывает символы и по a — A разному. For example, this command treats the characters a and A differently. Однако при использовании параметра /i Поиск выполняется без учета регистра, а в a A качестве того же символа обрабатывается и. 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.
Параметры и параметры командной строки для команды Find можно вводить в любом порядке. 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. Для поиска строки в наборе файлов, указанных с помощью подстановочных знаков, эту команду можно использовать в команде for . To search for a string in a set of files that you specify with wildcards, you can use this command within a for command.
При использовании /c и /v в одной командной строке эта команда отображает количество строк, которые не содержат указанную строку. 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. При указании параметра /c и /n в той же командной строке команда Find игнорирует параметр /n. 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
Чтобы отобразить все строки из Pencil.AD , которые содержат строку резкость карандаша, введите: 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.» в файле report.doc введите: in the report.doc file, type:
Для поиска набора файлов можно использовать команду Find в команде for . To search for a set of files, you can use the find command within the for command. Чтобы найти в текущем каталоге файлы с расширением bat, которые содержат строку строки, введите следующую команду: To search the current directory for files that have the extension .bat and that contain the string PROMPT, type:
Чтобы найти и отобразить имена файлов на диске C, которые содержат строковый ЦП, выполните поиск на жестком диске с помощью вертикальной черты (|), чтобы направить выходные данные команды dir в команду Find следующим образом: 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:
Так как поиск при поиске выполняется с учетом регистра, а dir создает прописные буквы, необходимо либо ввести строковый процессор в верхнем регистре, либо использовать параметр командной строки /i с командой Find. 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 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.
Find windows OS version from command line
Windows has command line utilities that show us the version of the Windows OS running on the computer, including the service pack number. There are multiple CMD commands that help with finding this, you can pick the one that suits your need. Ver command can show you the OS version whereas Systeminfo command can additionally give you service pack, OS edition and build number etc.
Find OS Version and Service Pack number from CMD
As you can see above, ver command shows only OS version but not the service pack number. We can find service pack number as well with Systeminfo command. Systeminfo dumps lot of other information too, which we can filter out using findstr command.
This command works on XP, Vista and Windows 7 and on Server editions also. Find below example for Win7.
In case of Windows 7 SP1, the output would be slightly different as below.
If you want to print more details, then you can use just ‘OS’ in the findstr search pattern. See example below for Server 2008.
Check Windows version using WMIC command
Run the below WMIC command to get OS version and the service pack number.
Example on Windows 7:
If you want to find just the OS version, you can use ver command. Open command window and execute ver command. But note that this does not show service pack version.
This command does not show version on a Windows 7 system.