Время на прочтение
2 мин
Количество просмотров 158K
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 перенёс в «Системное администрирование»
The grep
command in Linux is widely used for parsing files and searching for useful data in the outputs of different commands.
The findstr
command is a Windows grep
equivalent in a Windows command-line prompt (CMD).
In a Windows PowerShell the alternative for grep
is the Select-String
command.
Below you will find some examples of how to “grep” in Windows using these alternatives.
Cool Tip: Windows touch
command equivalent in CMD and PowerShell! Read more →
Grep Command in Windows
Grep the output of a netstat
command for a specific port:
# Windows CMD C:\> netstat -na | findstr /c:"PORT" # Windows PowerShell PS C:\> netstat -na | Select-String "PORT"
If a command in PowerShell returns some objects, before parsing, they should be converted to strings using the Out-String -Stream
command:
# Windows CMD
PS C:\> Get-Alias | Out-String -Stream | Select-String "curl"
Grep a file for a pattern that matches a regular expression (case insensitive):
# Windows CMD C:\> findstr /i /r /c:"^SEARCH.*STRING$" file.txt # Windows PowerShell PS C:\> Select-String "^SEARCH.*STRING$" file.txt
Options used by the findstr
command in the example above:
Option | Description |
---|---|
/i |
Case-insensitive search. |
/c:"string" |
Use string as a literal search string. Without this option if the search string contains multiple words, separated with spaces, then findstr will return lines that contain either word (OR). |
/r |
Evaluate as a regular expression. |
Display help
for the Windows grep
command equivalents:
# Windows CMD C:\> findstr /? # Windows PowerShell PS C:\> get-help Select-String
Cool Tip: Windows cat
command equivalent in CMD and PowerShell! Read more →
Was it useful? Share this post with the world!
- Home
- OS
- Windows
- Команда findstr аналог grep для Windows
Команда findstr — используется для поиска строк в файлах, является аналогом команды grep в Linux.
Для тех, кто привык набирать команду grep, есть возможность задать алиас для команды findstr
Пример:
echo findstr %1 %2 %3 %4 %5 > %systemroot%\grep.cmd
FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:файл] [/C:строка] [/G:файл] [/D:список_папок] [/A:цвета] [/OFF[LINE]] строки [[диск:][путь]имя_файла[ ...]] /B - Искать образец только в началах строк. /E - Искать образец только в конце строк. /L - Поиск строк дословно. /R - Поиск строк как регулярных выражений. /S - Поиск файлов в текущей папке и всех ее подпапках. /I - Определяет, что поиск будет вестись без учета регистра. /X - Печатает строки, которые совпадают точно. /V - Печатает строки, не содержащие совпадений с искомыми. /N - Печатает номер строки, в которой найдено совпадение. /M - Печатает только имя файла, в котором найдено совпадение. /O - Печатает найденные строки через пустую строку. /P - Пропускает строки, содержащие непечатаемые символы. /OFF[LINE] - Не пропускает файлы с установленным атрибутом "Автономный". /A:цвета - Две шестнадцатеричные цифры - атрибуты цвета. См. "COLOR /?" /F:файл - Читает список файлов из заданного файла (/ для консоли). /C:строка - Использует заданную строку как искомую фразу поиска. /G:файл - Получение строк из заданного файла (/ для консоли). /D:список_папок - Поиск в списке папок (разделяются точкой с запятой). строки - Искомый текст. [диск:][путь]имя_файла - Задает имя файла или файлов.
Использовать пробелы для разделения нескольких искомых строк, если аргумент не имеет префикса /C.
Например, ‘FINDSTR «Привет мир» a.b’ ищет «Привет» или «мир» в файле a.b, а команда ‘FINDSTR /C:»Привет мир» a.b’ ищет строку «Привет мир» в файле a.b.
Краткая сводка по синтаксису регулярных выражений:
. - Любой символ. * - Повтор: ноль или более вхождений предыдущего символа или класса. ^ - Позиция в строке: начало строки. $ - Позиция в строке: конец строки. [класс] - Класс символов: любой единичный символ из множества. [^класс] - Обратный класс символов: любой единичный символ из дополнения. [x-y] - Диапазон: любые символы из указанного диапазона. \x - Служебный символ: символьное обозначение служебного символа x. \<xyz - Позиция в слове: в начале слова. xyz\> - Позиция в слове: в конце слова.
На этом все. Командочка нужная, надеюсь пригодиться.
Is there a similar utility to grep
available from the Windows Command Prompt, or is there a third party tool for it?
Roman C
49.9k33 gold badges66 silver badges176 bronze badges
asked Sep 12, 2009 at 21:48
Chintan ShahChintan Shah
3,1534 gold badges30 silver badges39 bronze badges
2
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.
answered Sep 12, 2009 at 21:51
5
PowerShell (included as standard on Windows 7/2008R2, optional for XP/2003/Vista/2008) which includes the select-string
cmdlet for this purpose.
answered Sep 12, 2009 at 21:59
RichardRichard
107k21 gold badges203 silver badges265 bronze badges
2
as mentioned, findstr works fine. example :
C:>dir | findstr Windows
11/06/2013 09:55 PM Windows
answered Dec 30, 2013 at 20:07
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)
answered Sep 13, 2009 at 2:13
SvendSvend
7,9163 gold badges30 silver badges45 bronze badges
0
answered Sep 12, 2009 at 22:36
sdusdu
2,7504 gold badges31 silver badges30 bronze badges
2
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.
Hope It helps.
answered Jul 31, 2012 at 1:13
Chintan ShahChintan Shah
3,1534 gold badges30 silver badges39 bronze badges
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.
answered Sep 13, 2009 at 2:16
Diaa SamiDiaa Sami
3,25924 silver badges31 bronze badges
1
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.
answered Apr 21, 2014 at 9:26
anatoly techtonikanatoly techtonik
19.9k9 gold badges124 silver badges142 bronze badges
UnxUtils is a great set of Unix utilites that run on Windows. It has grep, sed, gawk, etc.
answered Sep 12, 2009 at 22:03
Andy WhiteAndy White
86.6k48 gold badges176 silver badges211 bronze badges
2
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.
answered Dec 6, 2011 at 19:26
JPagetJPaget
96910 silver badges13 bronze badges
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:
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
answered Apr 5, 2018 at 20:58
woodviwoodvi
1,91821 silver badges27 bronze badges
3
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!
answered Sep 13, 2009 at 4:06
JubalJubal
8,4075 gold badges29 silver badges30 bronze badges
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.
Good Luck
answered Oct 16, 2017 at 19:42
DhugalmacDhugalmac
55410 silver badges20 bronze badges
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.
answered Sep 14, 2009 at 21:58
GBegenGBegen
6,1073 gold badges32 silver badges52 bronze badges
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…
answered May 17, 2011 at 18:35
stankovskistankovski
2,1292 gold badges16 silver badges11 bronze badges
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.
answered Oct 13, 2017 at 14:07
ShixxShixx
497 bronze badges
Use Cygwin…
it has 32 and 64 bits versions
and it works fine from Windows 2000 (*)
to Windows 10 or Server 2019
I use Cygwin for a long time…
and recently tryed to substitute with Windows-Linux-Subsystems…
not for long…
I quickly went back to Cygwin again…
much more flexible, controlable and rich…
also less intrusive…
just add \bin to the path…
and you can use it anyware in Windows/Batch/Powershell…
or in a DOS-Box… or in a Powershell-Box…
Also you can install a ton of great packages
that really work… like nginX or PHP…
I even use the Cygwin PHP package in my IIS…
As a bonus wou can also use it from a bash shell…
(I think this was the original intent ;-))
answered Apr 24, 2019 at 15:44
ZEEZEE
2,9515 gold badges35 silver badges48 bronze badges
Bare Grep is nice if you want a GUI. Gnu grep is good for CLI
answered Sep 12, 2009 at 22:11
ArielAriel
8726 silver badges11 bronze badges
If you don’t mind a paid-for product, PowerGREP is my personal favorite.
answered Sep 12, 2009 at 22:13
David AndresDavid Andres
31.4k7 gold badges46 silver badges36 bronze badges
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.
answered Sep 12, 2009 at 22:32
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.
answered Sep 13, 2009 at 1:29
Ron RubleRon Ruble
3061 silver badge8 bronze badges
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)
answered Feb 4, 2010 at 16:13
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.
answered Feb 4, 2010 at 16:20
btabta
44.1k6 gold badges69 silver badges99 bronze badges
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.
answered Feb 4, 2010 at 16:34
GreenMattGreenMatt
18.3k7 gold badges53 silver badges79 bronze badges
There’s a commercial grep utility available from Oak Road Systems.
answered Dec 6, 2011 at 19:22
JPagetJPaget
96910 silver badges13 bronze badges
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.
answered Mar 24, 2015 at 0:49
I know that it’s a bit old topic but, here is another thing you can do. I work on a developer VM with no internet access and quite limited free disk space, so I made use of the java installed on it.
Compile small java program that prints regex matches to the console. Put the jar somewhere on your system, create a batch to execute it and add the folder to your PATH variable:
JGrep.java:
package com.jgrep;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JGrep {
public static void main(String[] args) throws FileNotFoundException, IOException {
int printGroup = -1;
if (args.length < 2) {
System.out.println("Invalid arguments. Usage:");
System.out.println("jgrep [...-MODIFIERS] [PATTERN] [FILENAME]");
System.out.println("Available modifiers:");
System.out.println(" -printGroup - will print the given group only instead of the whole match. Eg: -printGroup=1");
System.out.println("Current arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println("args[" + i + "]=" + args[i]);
}
return;
}
Pattern pattern = null;
String filename = args[args.length - 1];
String patternArg = args[args.length - 2];
pattern = Pattern.compile(patternArg);
int argCount = 2;
while (args.length - argCount - 1 >= 0) {
String arg = args[args.length - argCount - 1];
argCount++;
if (arg.startsWith("-printGroup=")) {
printGroup = Integer.parseInt(arg.substring("-printGroup=".length()));
}
}
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
}
Matcher matcher = pattern.matcher(sb.toString());
int matchesCount = 0;
while (matcher.find()) {
if (printGroup > 0) {
System.out.println(matcher.group(printGroup));
} else {
System.out.println(matcher.group());
}
matchesCount++;
}
System.out.println("----------------------------------------");
System.out.println("File: " + filename);
System.out.println("Pattern: " + pattern.pattern());
System.out.println("PrintGroup: " + printGroup);
System.out.println("Matches: " + matchesCount);
}
}
c:\jgrep\jgrep.bat (together with jgrep.jar):
@echo off
java -cp c:\jgrep\jgrep.jar com.jgrep.JGrep %*
and add c:\jgrep in the end of the PATH environment variable.
Now simply call jgrep "expression" file.txt
from anywhere.
I needed to print some specific groups from my expression so I added a modifier and call it like jgrep -printGroup=1 "expression" file.txt
.
answered Jan 29, 2018 at 16:09
mihailmihail
2,17319 silver badges31 bronze badges
Is there a command prompt grep equivalent for Windows 7? That is, I want to filter out the results of a command:
Bash use:
ls | grep root
What would it be from a Windows command prompt?
jww
11.9k44 gold badges120 silver badges209 bronze badges
asked Jun 22, 2011 at 20:51
1
Findstr sounds like what you want. I use it all the time as an approximate grep-equivalent on the Windows platform.
Another example with pipes:
C:\> dir /B | findstr /R /C:"[mp]"
answered Jun 22, 2011 at 21:00
Greg JacksonGreg Jackson
3,5352 gold badges17 silver badges15 bronze badges
10
There are several possibilities:
- Use a port of a Unix
grep
command. There are several choices. Oft-mentioned are GNUWin32, cygwin, and unxutils. Less well known, but in some ways better, are the tools in the SFUA utility toolkit, which run in the Subsystem for UNIX-based Applications that comes right there in the box with Windows 7 Ultimate edition and Windows Server 2008 R2. (For Windows XP, one can download and install Services for UNIX version 3.5.) This toolkit has a large number of command-line TUI tools, frommv
anddu
, through the Korn and C shells, toperl
andawk
. It comes in both x86-64 and IA64 flavours as well as x86-32. The programs run in Windows’ native proper POSIX environment, rather than with emulator DLLs (such ascygwin1.dll
) layering things over Win32. And yes, the toolkit hasgrep
, as well as some 300 others. - Use one of the many native Win32
grep
commands that people have written and published. Tim Charron has a native Win32 version of a modified GNU grep, for example. There are also PowerGREP, Bare Grep, grepWin, AstroGrep, and dnGrep, although these are all GUI programs not TUI programs. - Use the supplied
find
andfindstr
. The syntax is different to that ofgrep
, note, as is the regular expression capability.
John M
2271 gold badge3 silver badges12 bronze badges
answered Jun 23, 2011 at 13:06
JdeBPJdeBP
26.7k1 gold badge72 silver badges103 bronze badges
3
If PowerShell commands are allowed, use
PS C:\> Get-ChildItem | Select-String root
or short
PS C:\> ls | sls root
Be aware that the alias sls
is only defined beginning with PowerShell version 3.0. You may add an alias for less typing:
PS C:\> New-Alias sls Select-String
To run the PowerShell command directly from cmd, use
C:\>powershell -command "ls | select-string root"
answered Jan 13, 2014 at 13:16
oleschrioleschri
1,1759 silver badges16 bronze badges
1
In your early revision you wrote MS-DOS, there’s only FIND
, as far as I know. But it’s an ancient OS not used anymore.
In the Windows NT command prompt(e.g. Win2K and win XP and later, so e.g. win7,win10), you can use find
and findstr
and if you download GnuWin32 then grep
The basic differences are that findstr has some regular expressions support. Grep supports regular expressions best.
C:\>dir | find "abc"
C:\>dir | find /i "abc"
find /?
and findstr /?
shows you what the switches do.
Gnuwin32 has «packages». If you download GnuWin32, I suggest the coreutils package for a bunch of basic useful utilities you’d be familiar with, but grep isn’t in that one it’s its own package.
Added
GnuWin32’s grep, last time I checked, is old. Cygwin’s grep is far more up to date. Also bear in mind that many people use Virtual Machines rather than windows ports of *nix commands.
answered Jun 22, 2011 at 21:00
barlopbarlop
23.5k43 gold badges146 silver badges226 bronze badges
If you would rather use grep
, rather than findstr
, there is a single .exe
file version in UnxUtils, so it’s portable and there is no need to install it, or use something like Cygwin.
answered Jun 22, 2011 at 21:07
paradroidparadroid
22.8k10 gold badges76 silver badges114 bronze badges
5
Bash use
$ ls | grep root
Cmd use
> dir /b | findstr root
where /b
stands for bare list of directories and files
answered May 2, 2016 at 5:47
5
You can try installing Chocolatey on Windows, and through that, install the Gow tool. This will provide you with grep
on Windows.
Gow
stand for GNU on Windows. It provides Unix command line utilities on Windows.
answered Sep 11, 2014 at 5:33
AturAtur
5455 silver badges11 bronze badges
4
I wrote a Windows alternative to grep using Hybrid Batch/JScript code. I wrote this because getting the escape characters right in the GNU Win32 grep port was a real pain. This version works much more like how you would want the GNU version to work in Windows:
@set @junk=1 /*
@cscript //nologo //E:jscript %~f0 %*
@goto :eof */
var args=WScript.Arguments, argCnt=args.Length, stdin=WScript.StdIn, stdout=WScript.StdOut;
var replaceSingleQuotes=false, printMatchesOnly=false, matchString, flagString, regex, argDx=0;
if(argCnt==0) {
throw new Error("You must provide search criteria.");
}
flagString=""
if(argCnt>1) {
for(var bLoop=true; bLoop&&argDx<argCnt-1; argDx++) {
switch(args(argDx)) {
case '-t': replaceSingleQuotes=true; break;
case '-o': printMatchesOnly=true; break;
case '-g': flagString+="g"; break;
case '-i': flagString+="i"; break;
case '-m': flagString+="m"; break;
default: bLoop=false; break;
}
}
}
if(replaceSingleQuotes) {
matchString=args(argCnt-1).replace("'", '"');
} else {
matchString=args(argCnt-1);
}
if(printMatchesOnly) {
while(!stdin.AtEndOfStream) {
var sLine=stdin.ReadLine();
if(flagString.Length) regex=new RegExp(matchString, flagString);
else regex=new RegExp(matchString);
var m,matches=[],startDx=0;
while((m=regex.exec(sLine.substr(startDx))) !== null) {
stdout.WriteLine(m[0]);
startDx+=m.lastIndex;
}
}
} else {
if(flagString.Length) regex=new RegExp(matchString, flagString);
else regex=new RegExp(matchString);
while(!stdin.AtEndOfStream) {
var sLine=stdin.ReadLine();
if(regex.test(sLine)) {
stdout.WriteLine(sLine);
}
}
}
You can always find the latest version on my Gist page for this.
phuclv
26.7k15 gold badges115 silver badges235 bronze badges
answered Mar 3, 2015 at 11:06
krowekrowe
5,4931 gold badge24 silver badges31 bronze badges
http://www.multireplacer.com
Multi replacer program has been prepared so that many functions can be carried out by using
command line parameters. Command line usage is seen below:
MultiReplacer [Multi Replacer File] | [Search files] | [Search folders]
[-Subs] [-NoSubs] [-IncPtr=pattern] [-ExcPtr=patterns] [-DestDir=destination]
[-DMAnyTime]
[-DMWithinanhour] [-DMToday] [-DMYesterday] [-DMThisweek] [-DMThismonth]
[-DMThisYear]
[-CDMAfter=date] [-CDMBefore=date] [-MinFileSize=bytes count]
[-MaxFileSize=bytes count]
[-Search=text] [-Case] [-NoCase] [-Regex] [-NoRegex] [-SubMatchText=text]
[-ReplaceText=text]
[-StartSearch] [-StartReplace] [-AutoClose] [-StopAfterMatchThisFile] [-StopAfterMatchAll]
[-ExtractedWordsFile=filename] [-ExtractedLinesFile=filename] [-
ReportFile=filename]
answered Feb 8, 2014 at 22:15
You can still use your familiar grep
and other Linux commands by downloading this tool UnxUtils and add it location to your PATH
environment variable
answered Sep 3, 2014 at 2:48
thucnguyenthucnguyen
1,0797 silver badges4 bronze badges
1
I would suggest using busybox-w32, since it is only about 500 KB in size and actively maintained.
So that in your case, in the command prompt, it is:
busybox ls | busybox grep root
You can use doskey
in a command prompt launch by a batch file to make a command, like:
doskey ls="path\to\busybox.exe" ls $*
doskey grep="path\to\busybox.exe" grep $*
Then you can use ls | grep root
on the command prompt.
answered Jun 12, 2016 at 12:31
kisssonkissson
731 gold badge1 silver badge5 bronze badges
1
If you want to add the simplest grep
to your windows environment, then navigate to c:\windows\system32
and add a little batch script by using this command:
echo findstr %1 > grep.bat
Now you can
dir | grep notepad.exe
which is really a scary mix of shit. So add another batch script for ls
as explained in this post
echo dir %1 > %systemroot%\system32\ls.bat
Now things look a bit familiar
ls | grep notepad
HTH
answered Jul 4, 2017 at 8:34
domihdomih
1256 bronze badges
findstr is the command equivalent to grep.
You can try using this:
ls | findstr root
Simplest solution regarding your request, that I’ve found here so far.
Cheers»
answered Jul 16, 2022 at 15:14
2
echo findstr %1 %2 %3 %4 %5 > %systemroot%\grep.cmd
That’s gonna be quick and dirty equivalent.
C:\Windows\system32>dir | grep xwiz
C:\Windows\system32>findstr xwiz
2009.06.10 23:03 4.041 xwizard.dtd
2009.07.14 03:39 42.496 xwizard.exe
2009.07.14 03:41 432.640 xwizards.dll
techraf
4,86211 gold badges25 silver badges40 bronze badges
answered Mar 25, 2016 at 8:35
1
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.