Аналог команды find в windows

Время на прочтение2 мин

Количество просмотров180K

grep

Многим любителям шела нравится чудная команда grep.
К сожалению, windows нативно не имеет такой команды, по этому некоторые ставят себе наборы различных консольных утилит в *nix стиле, включая grep.

Мне, как любителю посидеть в консоли Windows очень мешало отсутствие грепа, по этому мои скрипты под Win всегда были не так хороши, как могли бы быть. Но мои скрипты должны работать на любой (ну, или почти на любой) Windows, так как же быть?

К счастью, в Windows XP (и выше) появились две команды, которые призваны исправить положение — это find и более мощный вариант — findstr.

первая простая, и имеет явный недостаток — искомый текст надо заключать в кавычки. Не знаю, как вам — но мне очень не удобно печатать кавычки каждый раз :)

findstr же этого не требует, и к тому же позволяет искать используя мощь регулярных выражений.

Таким образом, теперь надо помнить, что мы не в bash\zsh\etc, а в Win, и набирать findstr вместо grep.

Ну а на своей машине я сделал следующее:
echo findstr %1 %2 %3 %4 %5 > %systemroot%\grep.cmd
теперь можно не задумываясь грепать вывод:

C:\WINDOWS>netstat -an | grep LISTEN

C:\WINDOWS>findstr LISTEN
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING
TCP 0.0.0.0:1963 0.0.0.0:0 LISTENING
TCP 10.198.17.58:139 0.0.0.0:0 LISTENING
TCP 127.0.0.1:1025 0.0.0.0:0 LISTENING
TCP 127.0.0.1:9050 0.0.0.0:0 LISTENING
TCP 127.0.0.1:9051 0.0.0.0:0 LISTENING
TCP 192.168.56.1:139 0.0.0.0:0 LISTENING

Ну и на закуску:

ifconfig:

echo IF "%1"=="-a" (ipconfig /all) ELSE (ipconfig %1) > %systemroot%\ifconfig.cmd

man:

echo %1 /?> %systemroot%\man.cmd

ls:

echo IF "%1"=="-a" (dir) ELSE (IF "%1"=="-al" (dir) ELSE (dir %1 %2 %3 %4 %5)) > %systemroot%\ls.cmd
Я часто на автомате даю ключ(и) -a(l) команде ls, по этому добавил их «обработку»

UPD перенёс в «Системное администрирование»

Команда «forfiles«, имеющаяся в командной строке Windows, выполняет поиск файлов по маске и по дате модификации!
Команда «forfiles» в Windows является аналогом команды «find«, имеющейся в Unix-семействе операционных систем.
Справочная страница по команде «forfiles» на сайте Microsoft:

https://docs.microsoft.com/en-us/window … s/forfiles

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

Код: Выделить всё
/? forfiles

Например, в моей системе Windows 10, формат даты для команды forfiles в справке описан так:

/D <дата> Выбор файлов, у которых дата последнего изменения
больше или равна (+) либо меньше или равна
(-) указанной дате при использовании формата
«dd.MM.yyyy»; либо файлов, у которых дата последнего
изменения больше или равна (+)
текущей дате плюс «dd» дней либо меньше или
равна (-) текущей дате минус «dd» дней.
Допустимым числом дней «dd» является любое
число в диапазоне 0 — 32768.
«+» используется по умолчанию, если знак не указан.

Т.е. вместо прямых слэшей нужно использовать точки, а дата идет перед месяцем.
Например 20 сентября 2018 года нужно указывать как «20.09.2018», а не «09/20/2018»!
Вывод списка файлов, изменённых после указанной даты с полным путём:

Код: Выделить всё
forfiles /S /D +20.09.2018 /C "cmd /c echo @PATH/@FILE"

Home » Blog » Equivalent of UNIX Grep command in Dos/Windows

Last updated: May 22, 2010

You can use the ‘type’ and ‘find’ command in Dos/Windows to get the equivalent output of the UNIX ‘cat’ and ‘grep’ commands. The ‘find’ command can be very useful when you are trying to search for a specific text or phrase over multiple files. The ‘find’ command also comes in handy when searching for all the occurrences of a specific text or phrase in all the files under all the sub-directories of a given directory.

The Type Command

The ‘type’ command in Dos simply displays the contents of a text file or files. To see the content of a file simply enter the following in the command prompt:
C:>type “filename”

The Find Command

The ‘find’ command in Dos can be used to search for a text string in a file or files. below is the usage and optional parameters of the ‘find’ command.

FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]

/V         Displays all lines NOT containing the specified string.
/C         Displays only the count of lines containing the string.
/N         Displays line numbers with the displayed lines.
/I         Ignores the case of characters when searching for the string.
/OFF[LINE] Do not skip files with offline attribute set.
"string"   Specifies the text string to find.
[drive:][path]filename
Specifies a file or files to search.

If a path is not specified, FIND searches the text typed at the prompt or piped from another command.

Find Command Usage Examples

To find any text occurrence in all the files within a directory simply enter the following at the command prompt.

C:>find “text to find” *


D:\Project Material\find command example>find "text-align" *

---------- ADSENSE INSERTION TAG.TXT
<p style="text-align: center;"><!-- wp_ad_camp_1 --></p>
---------- CFORMS.PHP
echo '<p style="text-align: left;"><label for="cforms-title'.$no.'">';
---------- ROBOTS.TXT
---------- ROBOTS_LANGUAGE_FILTER.TXT
---------- TRANSLATION_PAGE.TXT

Use the ‘/n’ parameter to print out the line numbers.


D:\Project Material\find command example>find /n "text-align" *

---------- ADSENSE INSERTION TAG.TXT
[1]<p style="text-align: center;"><!-- wp_ad_camp_1 --></p>
[2]text-align
[3]Test line with the text text-align
[6]Another line with the desired text text-align

---------- CFORMS.PHP
[2269]          echo '<p style="text-align: left;"><label for="cforms-title'.$no.'">';

---------- ROBOTS.TXT

You can use ‘type’ and then pipe the output to the ‘find’ command:

D:\Project Material\find command example>type robots.txt | find /n "Disallow: /iw/"
[37]Disallow: /iw/

You can get really creative with these commands.

Reader Interactions

The FIND Command

To search for text in multiple files from the Windows command prompt or batch files, you can use the FIND command, which has been present since the days of MS DOS and is still available in Windows 11. It’s similar to the Unix grep command, but does not support regular expressions. If you want to search for the word borogoves in the current directory, please follow this syntax:

find "borogoves" *

Note that the double quotes around the pattern are mandatory. If you are using PowerShell, you will need to include single quotes as well:

find '"borogoves"' *

Instead of the asterisk (*), you can specify a file mask such as *.htm?. The find command displays the names of the files it scans, even if it doesn’t find any matches within these files:

The FIND command in Windows 11

The search is case-sensitive by default, so you typically need to add the /I switch to treat uppercase and lowercase letters as equivalent:

find /I "<a href=" *.htm

If you don’t specify the file to search in, find will wait for the text input from stdin, so that you can pipe output from another command. For example, you can list all copy commands supported in Windows:

help | find /i "copy"

Another switch, /V, allows you to find all lines not containing the pattern, similar to the grep -v command.

In batch files, you can use the fact that the find command sets the exit code (errorlevel) to 1 if the pattern is not found. For instance, you can check if the machine is running a 64-bit or 32-bit version of Windows:

@echo off 
rem Based on KB556009 with some corrections reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" /v "Identifier" | find /i "x86 Family" > nul if errorlevel 1 goto win64 
echo 32-bit Windows goto :eof 
:win64 rem Could be AMD64 or ARM64 echo 64-bit Windows

The FINDSTR Command: Regular Expression Search

If you need to find a regular expression, try the FINDSTR command, which was introduced in Windows XP. For historical reasons, findstr supports a limited subset of regular expressions, so you can only use these regex features:

  • The dot . matches any character except for newline and extended ASCII characters.
  • Character lists [abc] match any of the specified characters (a, b, or c).
  • Character list ranges [a-z] match any letter from a to z.
  • The asterisk (*) indicates that the previous character cane be repeated zero or more times.
  • The \< and \> symbols mark the beginning and the end of a word.
  • The caret (^) and the dollar sign ($) denote the beginning of and the end of a line.
  • The backslash (\) escapes any metacharacter, allowing you to find literal characters. For example, \$ finds the dollar sign itself.

Findstr does not support character classes (\d), alternation (|), or other repetitions (+ or {5}).

The basic syntax is the same as for the FIND command:

findstr "\<20[0-9][0-9]\>" *.htm

This command finds all years starting with 2000 in the .htm files of the current directory. Just like with find, use the /I switch for a case-insensitive search:

The FINDSTR command in Windows 11

FINDSTR Limitations and Quirks

Character lists [a-z] are always case-insensitive, so echo ABC | findstr "[a-z]" matches.

The space character works as the alternation metacharacter in findstr, so a search query like findstr "new shoes" * will find all lines containing either new or shoes. Unfortunately, there is no way to escape the space and use it as a literal character in a regular expression. For example, you cannot find lines starting with a space.

Syntax errors in regular expression are ignored. For instance, findstr "[" * will match all lines that contain the [ character.

If the file contains Unix line breaks (LF), the $ metacharacter does not work correctly. If the last line of a file lacks a line terminator, findstr will be unable to find it. For example, findstr "</html>$" * won’t work if there is no CR+LF after </html>.

Early Windows versions had limitations on line length for find and findstr, as well as other commands. The recent versions lifted these limits, so you don’t have to worry about them anymore. See this StackOverflow question for findstr limitations and bugs, especially in early Windows versions.

The findstr command operates in the OEM (MS DOS) code page; the dot metacharacter does not match any of the extended ASCII characters. As the result, the command is not very useful for non-English text. Besides that, you cannot search for Unicode characters (UTF-8 or UTF-16).

Conclusion

You can learn about other switches by typing findstr /? or find /?. For example, the additional switches allow you to search in subdirectories or print line numbers. You can also refer to the official documentation.

In general, the find and findstr commands are outdated and come with various quirks and limitations.

Command (computing)
Syntax (programming languages)
PowerShell
Microsoft Windows
Text file

    msm.ru

    Нравится ресурс?

    Помоги проекту!


    Правила раздела Windows

    1. Указывайте версию Вашей ОС.
    2. Запрещается размещать запросы и ссылки на кряки, серийники и т.п., а также вопросы нарушения лицензии ПО и его взлома.
    3. Не разрешается давать советы из разряда «Поставь Linux».
    4. Переустановка ОС — крайнее и безотказное лекарство, которое знают все. В таких советах никто не нуждается.
    5. При публикации скриптов пользоваться тегами code. Тип подсветки кода выбирать строго в соответствии с языком публикуемого кода.
    6. Прежде чем задать вопрос, обязательно загляните в FAQ и следуйте написанным рекомендациям для устранения проблемы. И если не помогло, а поиск по разделу не дал результатов — только тогда задавайте вопрос на форуме.
    7. Вопросы, связанные с проблемами ПО, задавайте в разделе Программное обеспечение


    аналог unix-овского ‘find’ в Windows

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,

      Подскажите, какой есть способ осуществить групповую операцию с файлами в консоли Windows по заданному условию поиска?
      В linux есть утилита ‘find’ — подходящая для этой цели.
      Конкретно нужно — автоматизировать ежедневное удаление из заданной папки файлов старше 30 суток (фильтруя по дате создания).


      FullArcticFox



      Сообщ.
      #2

      ,

        Белый и пушистый

        Рейтинг (т): 288

        Цитата harinag @

        Конкретно нужно — автоматизировать ежедневное удаление из заданной папки файлов старше 30 суток (фильтруя по дате создания).

        Я мыслю что лучше для этого воспользоваться скриптами, покопай в этой теме Полезные скрипты
        А так же тут http://forum.oszone.net/thread-146190.html — фактически готовое решение


        grgdvo



        Сообщ.
        #3

        ,

          есть еще GnuWin32. findutils входит

          0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

          0 пользователей:

          • Предыдущая тема
          • Windows
          • Следующая тема

          [ Script execution time: 0,0171 ]   [ 15 queries used ]   [ Generated: 14.05.25, 09:41 GMT ]  

          Понравилась статья? Поделить с друзьями:
          0 0 голоса
          Рейтинг статьи
          Подписаться
          Уведомить о
          guest

          0 комментариев
          Старые
          Новые Популярные
          Межтекстовые Отзывы
          Посмотреть все комментарии
        • Установить офис для windows 10 pro
        • Отключить страницу приветствия windows 10
        • Windows maximum packet size
        • Camhi для windows 10 на русском
        • Acpi sam0714 1 driver windows 10 64