FINDSTR
FINDSTR - это утилита для поиска текстовой строки в файле (или нескольких файлах). В отличие от простой команды FIND команда FINDSTR поддерживает более сложные регулярные выражения.
Синтакс
FINDSTR строка(и) [имя файла(ов)] [/R] [/C:"строка"] [/G:СтрокиФайл] [/F:файл] [/D:СписокПапок] [/A:цвет] [/OFF[LINE]] [options]
Параметры
string(s) Текст для поиска, каждое слово - отдельный поиск. pathname(s) Файл(ы) для поиска. /C:string Используйте строку в качестве точной строки поиска (может содержать пробелы). /R Ищет с помощью регулярного выражения. /R /C:string Использует строку в качестве регулярного выражения. /G:StringsFile Получение строки поиска из файла (/ обозначает консоль). /F:file Получить список имен файлов для поиска из файла (/ означает консоль). /d:dirlist Поиск списка каталогов, ограниченного запятыми. /A:color Отображение имен файлов в цвете (2 шестнадцатеричные цифры)
параметры могут комбинироваться из следующих переключателей:
/I Поиск без учета регистра. /S Поиск во вложенных папках. /P Пропускать все файлы, содержащие непечатаемые символы /OFF[LINE] Не пропускайте файлы с установленным атрибутом OffLine. /L Используйте поисковую строку (строки) точно. /B Совпадение с образцом, если он находится в начале строки. /E Совпадение с образцом, если он находится в КОНЦЕ строки. /X Выведите строки, которые точно совпадают. /V Print only lines that do NOT contain a match. /N Print the line number before each line that matches. /M Print only the filename if a file contains a match. /O Print character offset before each matching line.
При использовании /G или /F текстовый файл должен быть обычным текстовым файлом ANSI с одной строкой поиска или именем/путем в каждой строке. Если поиск ведется в нескольких файлах (/F), в результатах будет указано имя файла, в котором был найден текст. По умолчанию FINDSTR сопоставляет любое слово, поэтому FINDSTR "blue planet" сопоставит слово blue или слово planet. Чтобы сопоставить целую фразу/предложение или использовать регулярные выражения, воспользуйтесь опциями /C и /R.
Опции могут иметь префикс / или - Опции также могут быть объединены после одного / или -. Однако конкатенированный список опций может содержать не более одной многосимвольной опции, такой как OFF или F:, и многосимвольная опция должна быть последней в списке. Ниже приведены эквивалентные способы выражения нечувствительного к регистру regex-поиска для любой строки, содержащей "hello" и "goodbye" в любом порядке
FINDSTR /i /r /c:"hello.*goodbye" /c:"goodbye.*hello" Demo.txt FINDSTR -i -r -c:"hello.*goodbye" /c:"goodbye.*hello" Demo.txt FINDSTR /irc:"hello.*goodbye" /c:"goodbye.*hello" Demo.txt
Поиск более 2 элементов в любом порядке становится непрактичным, так как вам потребуются все перестановки. Альтернативным подходом является цепочка из нескольких команд findstr:
FINDSTR /ic:"hello" Demo.txt | findstr /ic:"goodbye"
Регулярные выражения (поиск шаблонов в тексте)
FINDSTR с опцией /R может использовать следующие метасимволы, которые имеют специальное значение либо как оператор, либо как разделитель. Поддержка FINDSTR для регулярных выражений ограничена и нестандартна, поддерживаются только следующие метасимволы:
. Подстановочный знак: любой символ. * Повтор: ноль или более повторений предыдущего персонажа или класса. ^ Положение в строке: начало строки. $ Положение в строке: конец строки. [class] Класс символов: любой один символ из набора. [aB4] будет соответствовать a или B или 4 [^class] Inverse class: any one character NOT in the set. [x-y] Range: any characters within the specified range \x Escape: literal use of metacharacter x. \<xyz Word position: beginning of word. xyz\> Word position: end of word.
Metacharacters are most powerful when they are used together. For example, the combination of the wildcard character (.) and repeat (*) character is similar in effect to the filename wildcard (*.*)
.* Match any string of characters.
The .* expression can be useful within a larger expression, for example a.*b will match any string beginning with A and ending with B. FINDSTR does not support alternation with the pipe character (|) multiple Regular Expressions can be separated with spaces, just the same as separating multiple words (assuming you have not specified a literal search with /C) but this might not be useful if the regex itself contains spaces. FINDSTR does not support UTF-16 files, but FIND does.
Позиция строки в регулярных выражениях, якоря ^ и $
- ^ соответствует началу входного потока, а также любой позиции, следующей сразу за <LF>. Поскольку FINDSTR также разрывает строки после <LF>, простое регулярное выражение "^" всегда будет соответствовать всем строкам внутри файла, даже бинарного. Поэтому, чтобы найти строку snark в начале строки, используйте ^snark
- $ соответствует любой позиции, непосредственно предшествующей <CR>. Это означает, что строка regex-поиска, содержащая $, никогда не совпадет ни с одной строкой текстового файла в стиле Unix, а также с последней строкой текстового файла Windows, если в ней отсутствует маркер EOL <CR><LF>. Поэтому, чтобы найти строку snark в конце строки, используйте snark$
Примечание - Как описано ниже, в перенаправляемых и перенаправляемых входных данных FINDSTR могут быть добавлены <CR><LF>, которых нет в источнике. Это может повлиять на регекс-поиск, в котором используется $. Строка поиска с символами (до ^) ИЛИ (после $) всегда не будет находить совпадения. $nevermatches^
Позициональные параметры /B /E /X
Позиционные опции работают так же, как ^ и $, за исключением того, что они также работают для литеральных строк поиска.
/B Функционирует так же, как и ^ в начале строки поиска regex. /E Функционирует так же, как и $ в конце строки поиска regex. /X функционирует так же, как и ^ в начале и $ в конце строки поиска regex.
- FINDSTR - Спецсимволы и ограничения по длине - Более подробно о том, как использовать строки поиска, включающие кавычки и/или обратные слеши. Кроме того, максимальная длина строки поиска зависит от версии ОС.
Диапазоны классов символов регулярных выражений [x-y]
Диапазоны символьных классов не работают так, как ожидается.
The problem is FINDSTR does not collate the characters by their byte code value (commonly thought of as the ASCII code, but ASCII is only defined from 0x00 - 0x7F). Most regex implementations would treat [A-Z] as all upper case English capital letters. But FINDSTR uses a collation sequence that roughly corresponds to how SORT works. So [A-Z] includes the complete English alphabet, both upper and lower case (except for "a"), as well as non-English alpha characters with diacriticals. The FINDSTR regex sorts lower case before upper case. So findstr /nrc:"^[A-a]" will find nothing, but findstr /nrc:"^[a-A]" will match.
Default type of search: Literal vs Regular Expression
/C:"string" - The default match like /L literal, but will also accept spaces. /R /C:"Search string" - This will perform a Regex match, but will also accept spaces in the search string. "string argument" - The default depends on the content of the very first search string. (Remember that <space> is used to delimit search strings.) If the first search string is a valid regular expression that contains at least one un-escaped meta-character, then all search strings are treated as regular expressions. Otherwise all search strings are treated as literals. For example, "51.4 200" will be treated as two regular expressions because the first string contains an un-escaped dot, whereas "200 51.4" will be treated as two literals because the first string does not contain any meta-characters. /G:file - The default depends on the content of the first non-empty line in the file. If the first search string is a valid regular expression that contains at least one un-escaped meta-character, then all search strings are treated as regular expressions. Otherwise all search strings are treated as literals. Recommendation - Always explicitly specify /L literal option or /R regular expression option when using "string argument" or /G:file.
Поиск пробелов
Если строка поиска содержит несколько слов, разделенных пробелами, то FINDSTR вернет строки, содержащие любое из слов (OR). Буквальный поиск (/C: "string") изменит это поведение и позволит искать фразу или предложение. Буквальный поиск также позволяет искать знаки препинания. Некоторые примеры с использованием текстового файла Demo.txt, содержащего следующее:
The quick brown fox The really ^brown^ fox Буквальный поиск /L : Совпадает с первой сторокой: FINDSTR /L /C:"quick brown" Demo.txt Совпадает со второй строкой: FINDSTR /L /C:"^brown" Demo.txt
Поиск помощью регулярного выражения /R : Совпадает со словом "лиса" в конце любой строки с: FINDSTR /R /C:"fox$" Demo.txt Совпадает со словом The или the (без учета регистра) в начале любой строки с: FINDSTR /I /R /C:"^the" Demo.txt
FINDSTR Output
The format of matching line output from FINDSTR is: filename:lineNumber:lineOffset:text where fileName = The name of the file containing the matching line. The file name is not printed if the request was explicitly for a single file, or if searching piped input or redirected input. When printed, the fileName will always include any path information provided. Additional path information will be added if the /S option is used. The printed path is always relative to the provided path, or relative to the current directory if none provided. lineNumber = The line number of the matching line represented as a decimal value with 1 representing the 1st line of the input. Only printed if /N option is specified. lineOffset = The decimal byte offset of the start of the matching line, with 0 representing the 1st character of the 1st line. Only printed if /O option is specified. text = The binary representation of the matching line, including any <CR> and/or <LF>. Nothing is left out of the binary output, such that this example that matches all lines will produce an exact binary copy of the original file: FINDSTR "^" FILE >FILE_COPY
Using a script file
Multiple search criteria can be specified with a script file /G Multiple FileNames to search can be specified with /F When preparing a source or script file, place each filename or search criteria on a new line. If several filenames are to be searched they must all exist or FINDSTR will fail with an error. For example: to use the search criteria in Criteria.txt to search the files listed in Files.txt: FINDSTR /g:Criteria.txt /f:Files.txt
Конвеер и перенаправление
Текстовый файл может быть передан через конвеер или перенаправлен в FINDSTR: ○ Data stream from a pipe TYPE file.txt | FINDSTR "searchString" ○ Stdin via redirection FINDSTR "searchString" <file.txt The various data source specifications are mutually exclusive - FINDSTR can only work with one of the following: filename argument(s), /F:file option, redirected input, or piped input. A string can also be piped into FINDSTR, this will just tell us if searchString exists within dataString: Echo "dataString"| FINDSTR "searchString" Piped and Redirected input can have <CR><LF> appended: ○ If the input is piped in and the last character of the stream is not <LF>, then FINDSTR will automatically append <CR><LF> to the input. (XP, Vista and Windows 7.) ○ If the input is redirected and the last character of the file is not <LF>, then FINDSTR will automatically append <CR><LF> to the input. (Vista only), Note that in this case XP and Windows 7/2008 will not alter redirected input which can cause FINDSTR to hang indefinitely.
Finding Unicode text under PowerShell
When running FINDSTR under the CMD shell, it can be used to match Unicode strings, but running a similar command under PowerShell will fail. This is because output data piped from a PowerShell cmdlet into a native application will default to ASCII. This is normally a sensible default because most native commands do not process Unicode correctly. The output encoding from PowerShell cmdlets is controlled by the $OutputEncoding variable, if that is set then FINDSTR will work against unicode text. $OutputEncoding = UnicodeEncoding or to match the console's encoding: $OutputEncoding = [Console]::OutputEncoding
Errorlevel
FINDSTR will set %ERRORLEVEL% as follows: 0 A match is found in at least one line of at least one file. 1 If a match is not found in any line of any file, (or if the file is not found at all). 2 Wrong syntax An invalid switch will only print an error message in error stream. Echo 12G6 |FindStr /R "[0-9]" If %ERRORLEVEL% EQU 0 echo The string contains one or more numeric characters Echo 12G6 |FindStr /R "[^0-9]" If %ERRORLEVEL% EQU 0 echo The string contains one or more non numeric characters
Bugs
If the last character of a file used as redirected input does not end with <LF>, then FINDSTR will hang indefinitely once it reaches the end of the redirected file. FINDSTR cannot search for null bytes commonly found in Unicode files. Specifying multiple literal search strings can give unreliable results. The following FINDSTR example fails to find a match, even though it should: echo ffffaaa|findstr /L "ffffaaa faffaffddd" Based on experiments, FINDSTR can fail if all of the following conditions are met: ○ The search is using multiple literal search strings ○ The search strings are of different lengths ○ A short search string has some amount of overlap with a longer search string ○ The search is case sensitive (no /I option) It seems to always be the shorter search strings that fails, for more info see: FINDSTR fails to match multiple literal search strings In early versions of FindStr /F:file a path length of more than 80 chars will be truncated.
Examples:
Search for "granny" OR "Smith" in the files Apples.txt or Pears.txt FINDSTR "granny Smith" Apples.txt Pears.txt
Search for "granny Smith" in Contacts.txt (effectively the same as the FIND command) FINDSTR /C:"granny Smith" Contacts.txt
Search every file in the current folder and all subfolders for the word "Smith", regardless of upper/lower case, note that /S will only search below the current directory:
FINDSTR /s /i smith *.*
Match exactly the number 12345: Echo 12345| findstr /X "12345"
Join two files, return only the lines that they both have in common: FINDSTR /g:"file1.txt" "file2.txt"
Search all the text files in the current folder for the string "fiona", display the filenames in White on Green (:2F). FINDSTR /A:2F /C:"fiona" *.txt
Read the file Z:\source.txt, remove all the blank lines and write to Z:\result.txt FINDSTR /v "^$" Z:\source.txt >Z:\result.txt
Find every line in novel.txt containing the word SMITH, preceeded by any number of spaces, and prefix each line found with a consecutive number:
FINDSTR /b /n /c:" *smith" novel.txt
Finding a string only if surrounded by the standard delimiters
Find the word "computer", but not the words "supercomputer" or "computerise": FINDSTR "\<computer\>" C:\work\inventory.txt
Find any words that begin with the letters 'comp', such as 'computerise' or 'compete' FINDSTR "\<comp.*" C:\work\inventory.txt
Find any positive integers in the file sales.txt and include any lines that are a zero (0): FINDSTR /r "^[1-9][0-9]*$ ^0$" Sales.txt
findstr test0001 file.txt
в файле file.txt ищем строку содержащую выражение user1 test
findstr /c:"user1 test" file.txt
ищем без учета регистра во всех файлах текущего каталога слово example
findstr /s /i example *.*
выбрать из всех лог файлов строки которые не содержат в себе выражения lab.user01
findstr /s /v lab.user01 *.log > result.txt
Если мы разбираем лог-файл IIS-а на предмет запрошенных файлов то вводим
type logfile01.log | findstr "file="
Если необходимо получить список запросов несуществующих файлов (ошибка 404) то вводим
type logfile01.log | findstr "404"
Для удобства есть опции /n и /m и их можно использовать для того что бы получить строку в которой находится искомое выражение или список имен файлов в которых есть выражение. Если необходимо найти по началу строки то в строке поиска используем
findstr /s /i "\<192.168.1.*" *.*
получаем всех кто обращался из указанной подсети. И в завершении… Для того что бы определить какие порты открыты на нашей системе пишем netstat -an | findstr 0.0.0.0