Grep analog in windows

Grep эквивалент для Windows 7?

Есть ли в командной строке grep эквивалент для Windows 7? То есть я хочу отфильтровать результаты команды:

Использование Bash:

Что бы это было из командной строки Windows?

Findstr звучит как то, что вы хотите. Я использую его все время как приблизительный эквивалент grep на платформе Windows.

Есть несколько возможностей:

  • Используйте порт команды Unix grep . Есть несколько вариантов. Чаще всего упоминаются GNUWin32 , cygwin и unxutils . Менее известными, но в некотором смысле лучше, являются инструменты из служебного инструментария SFUA , которые запускаются в Подсистеме для приложений на основе UNIX, которая поставляется в комплекте с Windows 7 Ultimate Edition и Windows Server 2008 R2. (Для Windows XP, можно загрузить и установить службы для UNIX версии 3.5 .) Этот инструментарий имеет большое количество командной строки TUI инструментов, от mv и du через оболочки Korn и C, чтобы perl и awk , Он выпускается в версиях x86-64 и IA64, а также x86-32. Программы работают в собственном POSIX-окружении Windows, а не с DLL-библиотеками эмулятора (такими как cygwin1.dll ), наслоенными поверх Win32. И да, инструментарий есть grep , а также около 300 других.
  • Используйте одну из многих собственных grep команд Win32, которые люди написали и опубликовали. Тим Чаррон, например, имеет встроенную версию модифицированной GNU grep для Win32 . Существуют также PowerGREP , Bare Grep , grepWin , AstroGrep и dnGrep , хотя это все программы с графическим интерфейсом, а не программы TUI.
  • Используйте прилагаемые find и findstr . grep Обратите внимание, что синтаксис отличается от синтаксиса регулярных выражений.

Is there a Pattern Matching Utility like GREP in Windows?

Is there a similar utility to grep available from the Windows Command Prompt, or is there a third party tool for it?

32 Answers 32

There is a command-line tool called FINDSTR that comes with all Windows NT-class operating systems (type FINDSTR /? into a Command Prompt window for more information) It doesn’t support everything grep does but it might be sufficient for your needs.

PowerShell (included as standard on Windows 7/2008R2, optional for XP/2003/Vista/2008) which includes the select-string cmdlet for this purpose.

Grep for Windows by GnuWin Project (2014-10-02: It’s outdated, see comments below)

as mentioned, findstr works fine. example :

C:>dir | findstr Windows

11/06/2013 09:55 PM Windows

I also found one more way of utilizing GREP like functionality in Windows 7 and above without any extra application to install and on older systems you can use install Powershell.

In Powershell, User can use Where-Object it has quite comprehensive set of feature that provides all the functionality of GREP plus more.

I’m surprised no one has mentioned FINDSTR. I’m no grep poweruser, but findstr does what I need it to, filter files and stdin, with some primitive regex support. Ships with Windows and all that. (Edit: Well someone did mention findstr, It’s late I guess)

GnuWin32 is worth mentioning, it provides native Win32 version of all standard linux tools, including grep, file, sed, groff, indent, etc.

And it’s constantly updated when new versions of these tools are released.

Читайте также:  Настройка windows server маршрутизатора

UnxUtils is a great set of Unix utilites that run on Windows. It has grep, sed, gawk, etc.

On Windows I use Far Manager for file search. BSD licensed, works in console, saves time on typing cmdline parameters. Here is its search dialog invoked by Alt-F7.

Update: This wasn’t true when the question was originally asked, but now Microsoft lets one Install the Windows Subsystem for Linux, and Windows will then run grep. In PowerShell, run:

An excellent and very fast file search utility, Agent Ransack, supports regular expression searching. It’s primarily a GUI utility, but a command-line interface is also available.

In the windows reskit there is a utility called «qgrep». You may have it on your box already. 😉 It also comes with the «tail» command, thank god!

Although not technically grep nor command line, both Microsoft Visual Studio and Notepad++ have a very good Find in Files feature with full regular expression support. I find myself using them frequently even though I also have the CygWin version of grep available on the command line.

I’ll add my $0.02 to this thread. dnGREP is a great open source grep tool for windows that supports undo, windows explorer integration, search inside PDFs, zips, DOCs and bunch of other stuff.

Yes there is only one program for Windows PC which have solid GUI and it is essential util for me. I work as a developer and on every computer I’ve had, first thing install XFind program. It is created in 1997 and till now version is 1.0 and till now works and it is the best. Frequently I need to search some string in a «.cs», «.aspx», «.sct» (Visual FoxPro form code file) or just «.*» and XFind scans all files and show me files and another great thing is that you can look where string is in the file. XFind has also some kind of editor. If it binary file it will show you string finded. Try it and use it forever if you are developer like me.

You have obviously gotten a lot of different recommendations.
My personal choice for a Free, 3rd Party Utility is: Agent Ransack
Agent Ransack Download
Despite its somewhat confusing name, it works well and can be used in a variety of ways to find files.

the all-in-one busybox contains grep / egrep / sed / awk and MANY more

Update: no longer available — or some older

Bare Grep is nice if you want a GUI. Gnu grep is good for CLI

If you don’t mind a paid-for product, PowerGREP is my personal favorite.

We have recently used PowerGREP for some fairly advanced bulk operations on thousands of files. Including regex searching in content of PDF files, and altering PDF documents in largescale.

Its worth the money if you want to save time from manuel labour. You can try it before you buy i think.

If you have to use bare Windows, then in addition to the Powershell option noted above, you can use VBScript, which has decent RegEx support.

MS also has a decent scripting area on Technet with a ton of examples for administrators.

Just try LikeGrep java utility. It may help you in very many cases. As you wish, it can also replace some text, found in files. It garantees its work on large files (up-to 8 Gb tested)

As mentioned above, the gnuwin32 project has a Windows CLI version of grep.

If you want something with a graphical interface, I would recommend the (open-source) tool AstroGrep.

Читайте также:  Кортана windows 10 приложение не работает как это исправить

It has been a while since I’ve used them, but Borland (Embarcadero now) included a command line grep with their C/C++ compiler. For some time, they have made available their 5.5 version as a free download after registering.

There’s a commercial grep utility available from Oak Road Systems.

I recommend PowerGrep

I had to do an e-discovery project several years ago. I found that fisdstr had some limitations, most especially fisdstr would eventually fail

the script had to search across thousands of files using a couple of dozen search terms/phrases.

Cygwin’s grep worked much better, it didn’t choke often, but ultimately I went to PowerGrep because the graphical interface made it much easier to tell when and where it crashed, and also it was really easy to edit in all the conditionals and output that I wanted. Ultimately PowerGrep was the most reliable of the three.

🧾 Как скачать, установить и использовать GNU Grep в Windows?

grep – очень мощный и полезный инструмент, используемый в операционных системах Linux и Unix.

Он в основном используется для сопоставления и вывода указанного текста в заданных текстовых файлах в разных форматах.

У grep также есть подверсии вроде egrep, которые предоставляют расширенные функциональные возможности, такие как регулярные выражения.

В этом руководстве мы узнаем, как загрузить, установить и использовать grep и egrep для операционных систем Windows.

Скачать GNU Grep

grep – это инструментальные средства Unix или Linux, предоставляемые как opensource.

Он также предоставляется GNU для операционных систем и платформ Windows.

Мы можем скачать установочный файл grep со следующей страницы.

Или просто мы можем скачать по следующей ссылке напрямую.

Но имейте в виду, что когда появятся новые версии, следующая ссылка будет устаревшей.

Установить GNU Grep

Мы начнем установку, щелкнув на файл gre-2.5.4-setup.exe.

Мы видим, что текущая версия программы установки, которую мы будем устанавливать, – 2.5.4.

Это может потребовать некоторых административных привилегий.

Таким образом, мы предоставим права администратора, нажав Да в диалоговом окне.

Под стартовым экраном установки GNU Grep

Далее следуйте подсказкам установщика в графическом режиме.

Задать путь Grep для переменных среды

В соответствии с заданной конфигурацией grep устанавливается в C:\Program Files\GnuWin32\ в каталоге bin.

Чтобы вызвать и использовать команду grep из MS-DOS или командной строки, нам нужно добавить этот путь к переменным среды PATHvariable.

Мы также можем увидеть исполняемые файлы с именами egrep, fgrep и grep на следующем экране.

Мы можем установить путь разными способами, но наиболее практичным является использование слишком setx командной строки, как показано ниже.

Затем мы можем проверить, открыв новую командную строку или окно MS-DOS и запустив команду grep, как показано ниже.

Мы можем увидеть, что команда grep установлена и ожидает некоторый параметр и файл для работы.

Вывести справочную информацию Grep

Команда grep в Windows очень похожа на версию для Linux. Но нам может понадобиться некоторая полезная информация об использовании и опциях. Мы можем напечатать справочную информацию с опцией –help, как показано ниже.

Поиск текста или слова с grep в Windows

Мы можем выполнить поиск определенного слова или текста, просто предоставив термин grep и файл, который мы хотим отобразить.

В этом примере термин grep – это ssh, а файл, который мы хотим посмотреть, называется config.txt.

Содержимое config.txt, как показано ниже, представляет собой файл ssh_config из коробки Ubuntu.

Мы запустим следующую команду:

Добавить комментарий Отменить ответ

• Свежие записи

• Категории

• itsecforu.ru

• Страны посетителей

IT is good

grep in windows batch file

I am trying to write a Windows batch file that will look through a specific html index file that looks something like this (simplified)

Читайте также:  Как определить что windows 10 активирована

and print all links whose filenames contain any uppercase letters so that they may be corrected not to so include any.

The following works in unix:

(the -v reverses the match)

But using the UnxUtils grep under Windows, which is a direct port of unix grep, I can’t come up with a way of quoting the regex that works. This would be necessary to use it in a batch file. I’ve tried ‘, » with no joy and also the -E switch. Is there any way to do this using this particular toolset?

@janos led me to the findstr command in Windows but it still doesn’t work. Looking at the findstr help I see:

FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file] [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]] strings [[drive:][path]filename[ . ]]

.
/V Prints only lines that do not contain a match. .
/C:string Uses specified string as a literal search string. .

Use spaces to separate multiple search strings unless the argument is prefixed with /C. For example, ‘FINDSTR «hello there» x.y’ searches for «hello» or «there» in file x.y. ‘FINDSTR /C:»hello there» x.y’ searches for «hello there» in file x.y.

However, this doesn’t work either:

Either findstr is garbage or there is some subtle difference from grep.

NETWORKS FOR EVERYONE

Grep – это утилита, которая выводит строки по заданному регулярному выражению. Для сетевого администратора она очень полезна для парсинга больших лог-файлов, например с Cisco ASA. Grep по текстовому файлу с логами размером 2GB занимает обычно несколько секунд.
В любой nix-подобной операционной системе grep уже предустановлен, но если в качестве рабочей станции сетевого администратора используется ОС Windows, то подобного инструмента как такового нет. В Windows есть утилиты командной строки find и findstr, но они работают помедленней чем grep и не такие гибкие. Поэтому я советую установить и использовать grep в Windows.
Нужно скачать Setup с сайта http://gnuwin32.sourceforge.net/packages/grep.htm и установить его.

После установки для удобства вызова grep из командной строки, чтобы не писать каждый раз полный путь к утилите, нужно добавить запись в PATH. PATH представляет собой переменную, которая содержит набор директорий с исполняемыми файлами. Для добавления записи в PATH нужно открыть окно “Система” (WIN+PAUSE), выбрать “Дополнительные параметры системы”, далее выбрать “Переменные среды…”.

В открывшемся окне двойным щелчком нажимаем на “PATH” и добавляем через знак “;” (точка с запятой) путь “C:\Program Files (x86)\GnuWin32\bin” и нажимаем “ОК”.

Далее открываем cmd и проверяем настройку командой “path” – в конце вывода команды должен добавиться путь до папки с утилитой grep.

Все, теперь можно пользоваться.

Приведу пример, как использую этот инструмент я. Например перед нами стоит задача достать из файла с логами все, что связано с определенным IP-адресом.

Я решаю такие задачи следующим образом:

Создаю папку в корне диска C:\tmp\

Далее перехожу в эту папку командой cd c:\tmp\

Далее выполняю следующую команду:

grep x.x.x.x C:\tmp\log.txt > grep-log.txt

Где x.x.x.x – ip адрес, который мы ищем, “C:\tmp\log.txt” – файл с логами, знак “>” – оператор перенаправления вывода команды в файл, “grep-log.txt” файл с выводом команды grep.

Так же grep удобно использовать для фильтрации вывода команды “netstat”. Сделать это можно через знак pipeline – “|”. Чтобы посмотреть все порты, которые находятся на хосте в статусе “LISTEN” можно использовать следующую команду:

netstat -an | grep LISTEN

Подробную справку по использованию grep можно получить командой

Оцените статью