- How To Download, Install and Use GNU Grep On Windows?
- Download GNU Grep
- Install GNU Grep
- Set Grep Path For Environment Variables
- Print Grep Help Information
- Grep Specified Word or Text
- NETWORKS FOR EVERYONE
- grep in windows batch file
- What are good grep tools for Windows? [closed]
- 28 Answers 28
- Based on recommendations in the comments, I’ve started using grepWin and it’s fantastic and free.
- Additional solutions
- Existing Windows commands
- Linux command implementations on Windows
- Grep tools with a graphical interface
- Additional Grep tools
How To Download, Install and Use GNU Grep On Windows?
grep is a very powerful and useful tool used in Linux and Unix operating systems. It is mainly used to match and print specified text in given text files in different formats. grep also have subversions like egrep which will provide extended functionality like regular expressions . In this tutorial, we will learn how to download, install and use grep and egrep for Windows operating systems.
Download GNU Grep
grep is a Unix or Linux tools provided as opensource. Hopefully, it is also provided for Windows operating systems and platform by GNU. We can download the grep setup file from the following page.
Download GNU Grep
Or simply we can download from the following link directly. But keep in mind that when new versions have arrived following link will be absolute or old.
Install GNU Grep
We will start the installation by clicking to the gre-2.5.4-setup.exe We can see that the current version of the grep we will install is 2.5.4 .
This may require some Administrative privileges. So we will provide the Admin privileges by click Yes to the dialog box.
Below the Setup Start Screen of the GNU Grep
We will accept the license agreement by clicking I accept the agreement like below.
Accept License Agreement
We will set the destination location to install grep where the default is C:\Program Files\GnuWin32 .
Grep Installation Location
We will select the components we want to install. Full Installation will install both Binaries and Documentation otherwise we can select or deselect these components easily.
Grep Components
We will set the Start Menu Name for the GNU Grep like below.
Here are sme additional tasks like Creating Document Shortcuts in Start Menu Folder and Download Sources .
Now we can start the installation with the specified configuration. We will just click to the Install button like below.
Start Installation
As grep is a very tiny tool it will install quickly and we will see the following installation completed successfully screen.
Set Grep Path For Environment Variables
As specified configuration the grep is installed to the C:\Program Files\GnuWin32\ under to the binary \bin directory. In order call and use grep command from the MS-DOS or command line we need to add this path to the environment variables PATH variable. We can also see the executable files named egrep , fgrep and grep in the following screen.
We set path different ways but the most practical one is using command line too setx like below.
Then we can check by opening a new command line or MS-DOS windows and run grep command like below.
We can see that grep command expects some option and file in order to work.
Print Grep Help Information
grep command in Windows is very similar to the Linux version. But we may need some helpful information about the usage and options. We can print help information with the —help option like below.
Print Grep Help Information
Grep Specified Word or Text
We can grep specified word or text just by providing the grep term and the file we want to grep. In this example grep term is ssh and the file we want to look is named config.txt . config.txt content is like below which is and ssh_config file from an Ubuntu box.
We will run the following command
Grep Specified Word or Text
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 можно получить командой
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)
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.
What are good grep tools for Windows? [closed]
Any recommendations on grep tools for Windows? Ideally ones that could leverage 64-bit OS.
I’m aware of Cygwin, of course, and have also found PowerGREP, but I’m wondering if there are any hidden gems out there?
28 Answers 28
Based on recommendations in the comments, I’ve started using grepWin and it’s fantastic and free.
(I’m still a fan of PowerGREP, but I don’t use it anymore.)
I know you already mentioned it, but PowerGREP is awesome.
Some of my favorite features are:
- Right-click on a folder to run PowerGREP on it
- Use regular expressions or literal text
- Specify wildcards for files to include & exclude
- Search & replace
- Preview mode is nice because you can make sure you’re replacing what you intend to.
Now I realize that the other grep tools can do all of the above. It’s just that PowerGREP packages all of the functionality into a very easy-to-use GUI.
From the same wonderful folks who brought you RegexBuddy and who I have no affiliation with beyond loving their stuff. (It should be noted that RegexBuddy includes a basic version of grep (for Windows) itself and it costs a lot less than PowerGREP.)
Additional solutions
Existing Windows commands
Linux command implementations on Windows
Grep tools with a graphical interface
Additional Grep tools
FINDSTR is fairly powerful, supports regular expressions and has the advantages of being on all Windows machines already.
Example usage: findstr text_to_find * or to search recursively findstr /s text_to_find *
GrepWin Free and open source (GPL)
I’ve been using grepWin which was written by one of the tortoisesvn guys. Does the job on Windows.
Update July 2013:
Another grep tool I now use all the time on Windows is AstroGrep:
Its ability to show me more than just the line search (i.e. the —context=NUM of a command-line grep) is invaluable.
And it is fast. Very fast, even on an old computer with non-SSD drive (I know, they used to do this hard drive with spinning disks, called platters, crazy right?)
It is free.
It is portable (simple zip archive to unzip).
Original answer October 2008
Gnu Grep is alright
You can download it for example here: (site ftp)
All the usual options are here.
That, combined with gawk and xargs (includes ‘find’, from GnuWin32), and you can really script like you were on Unix!
PowerShell’s Select-String cmdlet was fine in v1.0, but is significantly better for v2.0. Having PowerShell built in to recent versions of Windows means your skills here will always useful, without first installing something.
New parameters added to Select-String: Select-String cmdlet now supports new parameters, such as:
- -Context: This allows you to see lines before and after the match line
- -AllMatches: which allows you to see all matches in a line (Previously, you could see only the first match in a line)
- -NotMatch: Equivalent to grep -v o
- -Encoding: to specify the character encoding
I find it expedient to create an function gcir for Get-ChildItem -Recurse . , with smarts to pass parameters correctly, and an alias ss for Select-String . So you an write:
It may not exactly fall into the ‘grep’ category, but I couldn’t get by on Windows without a utility called AgentRansack. It’s a gui-based «find in files» utility with regex support. It’s dead simple to right-click on a folder, hit «ransack..» and find files containing what you’re looking for. Extremely fast too.
It’s been a couple of years since you asked the question, but I’d recommend AstroGrep (http://astrogrep.sourceforge.net).
It’s free, open source, and has a simple interface. I use it to search code all the time.
PowerShell has been mentioned a few times. Here is how you would actually use it in a grepish way:
It recursively searches all text files in the current directory tree for SomeString with case sensitivity.
Even better, run this:
Then to really make it magical, add the function alias to your PowerShell Profile and you can almost dull the pain of not having proper command line tools.
Cygwin includes grep. All the GNU tools amd Unix stuff works great on Windows if you install Cygwin.
ack works well on Windows (if you’ve got Perl). I find it better than grep for many uses.
Git on Windows = grep in cmd.exe
I just found out installing Git will give you some basic Linux commands: cat, grep, scp and all other good ones.
Install then add the Git bin folder to your PATH and then your cmd.exe has basic Linux functionality!
dnGREP is an open source grep tool for Windows. It supports a number of cool features including:
- Undo for replace
- Ability to search by right clicking on folder in explorer
- Advance search options such as phonetic search and xpath
- Search inside PDF files, archives, and Word documents
IMHO, it has a nice and clean interface too 🙂
I always use WinGREP, but I’ve had issues with it not letting go of files.
Well, beside the Windows port of the GNU grep at:
there’s also Borland’s grep (very similar to GNU one) available in the freeware Borland’s Free C++ Compiler (it’s a freeware with command line tools).
I have successfully used GNU utilities for Win32 for quite some time and it has a good grep as well as tail and other handy gnu utils for win32. I avoid the packaged shell and simply use the executables right in win32 command prompt.
The Tail that is packaged is quite a good little application as well.
I’m the author of Aba Search and Replace. Just like PowerGREP, it supports regular expressions, saving patterns for further use, undo for replacements, preview with syntax highlight for HTML/CSS/JS/PHP, different encodings, including UTF-8 and UTF-16.
In comparison with PowerGREP, the GUI is less cluttered. Aba instantly starts searching as you are typing the pattern (incremental search), so you can experiment with regular expressions and immediately see the results.
You are welcomed to try my tool; I will be happy to answer any questions.
I wanted a free grep tool for Windows that allowed you to right click on a folder and do a regex search of every file — without any nag screen.
The following is a quick solution based on the findstr mentioned in a previous post.
Create a text file somewhere on your hard drive where you keep long lived tools. Rename to .bat or .cmd and paste the following into it:
Then browse to the SendTo folder. On Windows 7 browse to %APPDATA%\Microsoft\Windows\SendTo and drag a shortcut of the batch file to that SendTo folder.
I renamed the shortcut to 1 GREP to keep it at the top of the SendTo list.
Things that I’d like to do next with this is pipe the output of findstr through something that would generate an html file so that you could click on each output line to open that file. Also, I don’t think it works with shortcuts to folders. I’d have to inspect the parameter and see if it contains «.lnk».