Most of you are familiar with pipe grep command in Linux. Here I am explaining the equivalent command in Windows command line.
Windows has two different command prompts. One is called the CMD and the other one is PowerShell.
PowerShell is more powerful and user friendly compared to the raw shell in windows. Most of the commands in CMD works in PowerShell, but the commands in PowerShell might not work in CMD.
What is grep command in Linux ?
grep is a command for performing filter and search operation in a file or a folder or in the output of another command.
The syntax of grep command is given below.
grep [options] pattern [files]
Options Description -c : This prints only a count of the lines that match a pattern -h : Display the matched lines, but do not display the filenames. -i : Ignores, case for matching -l : Displays list of a filenames only. -n : Display the matched lines and their line numbers. -v : This prints out all the lines that do not matches the pattern -e exp : Specifies expression with this option. Can use multiple times. -f file : Takes patterns from file, one per line. -E : Treats pattern as an extended regular expression (ERE) -w : Match whole word -o : Print only the matched parts of a matching line, with each such part on a separate output line.
-A n : Prints searched line and n lines after the result. -B n : Prints searched line and n line before the result. -C n : Prints searched line and n lines after before the result.
Sample usages are given below.
In the below example, the grep command filters and searches for the string “Flask” in the output of the command pip freeze
pip freeze | grep "Flask"
In the below example, the grep command searches for the string Amal in the file userlist.txt. The option -i performs case insensitive search inside the file.
grep -i "Amal" userlist.txt
grep command equivalent in Windows CMD
findstr is the command equivalent to grep.
Example is given below. In the below examples, the findstr will do an exact match
pip freeze | findstr "Flask"
netstat -an | findstr "80"
To search a string within a file, use findstr in the following way
findstr <search-string> <filename>
findstr Amal userlist.txt
More details of findstr command can be found in this official documentation.
grep command equivalent in Windows PowerShell
findstr command works in powershell. We have another command in powershell which is Select-String
An example usage is given below.
netstat -an | Select-String 80
For searching a string in the contents of a file, use the below syntax
Select-String <string-to-search> <file-name>
Select-String Amal userlist.txt
I hope this explanation is clear. Feel free to comment if you have any questions or suggestions.