Grep in windows powershell

Как искать в Powershell используя Select-String

В Powershell есть командлет, похожий на grep в Linux, Select-String. С помощью него мы можем искать как файлы, так и вхождения строк и, по желанию, используя регулярные выражения.

Для поиска внутри файла можно выполнить следующий командлет:

  • Path — путь до директории или документа. В моем случае будут искаться все файлы с расширением .txt, т.к. знак * говорит что мы не знаем что находится слева. Если путь не указан, то он используется по умолчанию, откуда запущен powershell.
  • Pattern — строка, которую мы ищем внутри файла. Этот ключ используется для регулярных выражений. Для использования простого поиска, без регулярки, нужно ставить -SimpleMatch

Мы можем искать не только в файлах, но и в самих строках:

  • InputObject — объект, в котором мы будем искать переменную
  • SimpleMatch — простое совпадение. В моем случае их два. Если «hello» или «idk» будет в строке, то команда вернет строку.

Если мы используем путь в какую-то папку, то мы можем включать и исключать какие-то свойства:

  • $path — переменная с путем, которая включает все файлы в папке «New Folder».
  • Include — включает все файлы. В моем случае с расширением .txt
  • Exclude — исключает все файлы, которые начинаются на text.
  • CaseSensitive — учет регистра. В powershell, по умолчанию, буква «а» и «А» одинаковые, а с этим ключом они будут разными.

Т.к. командлет ищет только в текущей папке, но мы можем использовать другой, который рассматривался тут, для более глубокого поиска файлов через Powershell:

  • Recurse — рекурсивный поиск т.е. поиск по всем папкам включительно.
  • Exclude — исключаем файлы с расширением mp3

Если в папке много файлов, то конечно быстрее будет сначала отфильтровать файлы через powershell Get-ChildItem, а затем искать в них нужные строки через Select-String.

С помощью такой команды мы можем исключить файлы, к которым у нас нет доступа иначе может быть ошибка:

  • NoMatch — говорит, что нам нужны только те строки, где нет «fix» или дословно «Не совпадает»
  • ErrorAction — со значением SilentlyContinue — говорит «не уведомлять об ошибках».

Разницу с Nomatch можно увидеть на картинке:

Если файл или строка в другой кодировке, то мы можем указать дополнительный ключ в виде -Encoding. Он может принимать следующие значения:

How to “grep” in PowerShell

PowerShell is awesome if you haven’t used it but it’s absolutely foreign if you’re used to Unix-like Bash-like shells. For instance, there’s no grep , and ls -al won’t work (but ls will and it’ll display all files with details!).

If you switch from Linux to Windows, you might be tempted to either install Cygwin or all of your GNU utilities. Or you might go the Linux subsystem route (which is a totally fair way to go) but if you want to go the PowerShell route, here’s a neat little tip!

What’s grep?

Grep is basically a utility that lets you filter some data using various patterns. There’s a LOT more to it but my own common usage of it is:

Читайте также:  Reset windows search powershell script

This will filter out the output of cat and return only commands that include ssh . I use this to remind myself of IPs of servers I’ve recently used. Or I might do this:

to get all of my webpack plugins, scripts, and figure out the latest version of webpack. It’s a handy utility, and I use it all the time. To filter lists of files in a folder and pipe them to another command or whatever else.

Grep is POWERFUL and it’s super featureful but I won’t get into that in this article.

So what does PowerShell have that’s the equivalent?

Introducing Select-String

One thing that’s immediately apparent about PowerShell is that its commands have better naming conventions. In fact, PS script is more like a programming language than Bash.

PowerShell piping is like Bash piping though it has some differences that I won’t go into right now.

Select-String supports regular expressions so you can also write more complicated stuff like:

This will extract the front-matter from this post.

How about searching through multiple files?

Absolutely! Grep has a pretty easy syntax for it: grep $PATTERN glob/pattern/** . An -r flag will recursively search through a path.

You might use it to identify where you’re using @select in your Angular application. @select is a decorator provided by the angular-redux store.

So what about PowerShell? In PowerShell, you have to specify an argument but the explicitness actually makes a lot of sense:

Cool, what about recursion? Err…well, to have true recursion working and scan “n” levels deep, you’ll need to string a few commands together so we’ll skip that for now.

Happy PowerShelling!

Advanced Examples

Before I leave, I’d like to impart some fun advanced commands. Like I said, PowerShell piping isn’t like Linux piping. One of the big differences is that PowerShell utilizes “objects”.

So here’s a great example:

What this will do is: find files and matches to our pattern in all of TypeScript files in our current directory, select only the information we want to see, and transform it into a nice looking table like so (edited to fit site width):

You can then save it into a file via Out-File like so:

Or output to a CSV:

What I love about PowerShell is that this stuff is built-in and it has sensible names. When I read bash scripts, it can be confusing. I mean, what does awk do? What about sed ? Can you infer their jobs based on their names? Or what their flags mean?

How To Grep Text Files With Powershell Grep or Select-String Cmdlet In Windows?

Linux provides tool named grep for filter text data or output according to given string or regular expression. This tool is popular amongst Linux system administrators. On the other side Windows operating systems generally lacks this tool and its functionality up to Powershell. Powershell provides Select-String commandlet to provide similar features and options the Linux grep tool provides. In this tutorial we will look different use cases with examples of Select-String tool.

Help about Select-String can be get with the following command.

Help

Search String In A File

One of the simplest usage and most used feature is simply searching given string in a file. We will provide following options

  • -Pattern specifies the string we are searching for

poet.txt is the file we search in.

Search String In A File

Search String In Multiple Files

In previous example we have searched given string in a single file but real world problems are more than that. We can search string in multiple files by providing file name or extension with the help asterisk. In this example we will search in all text files by specifying *.txt file name.

Читайте также:  Настройки электропитания windows 10 процессор

Search String In Multiple Files

Search Files Recursively

Now the most advanced file specification is searching files recursively. Recursively searching will look given string in all current folder and al subfolders. We will provide Get-ChildItem command to provide files recursively to the Select-String command like below.

Search Files Recursively

Case Sensitive Search

By default given strings are searched case insensitive. We can change this behaviour by using -CaseSensitve option like below.

Case Sensitive Search

Match Regular Expression

Regular expression provides to define more rich and structured string expressions. Select-String command also supports regular expressions. We can provide regular expressions into pattern too. In this example we will use regular expression E.*E to match string.

Match Whole Word

By default given search term or string is looked partially or on whole words. If we need to match whole word which is surrounded by white spaces we should put white spaces around the search term. We will search case search term as a whole word.

Match Whole Word

Display N Lines Before Match

If we are looking some part of the text and need to see previous lines of the matches we can provide -Context option whit the number of lines we want to print.

Display N Lines Before Match

Display N Lines After Match

We will use -Context options again but we will provide after part of the line numbers. In this example we will print 3 lines after the match.

Display N Lines After Match

Display N Line Before and After Match

Now we will provide both parameters to the -Context where before and after line numbers will be provided. In this example we will print 1 lines before match and 2 lines after match in a single shot.

Display N Line Before and After Match

Highlighting Matches

In a result where there are a lot of match and text seeking the match specifically very hard. Highlighting the match will make the job easier.

Invert Match or Not Match

Another useful feature is printing not matched lines or invert match. This is like logic NOT operation. We will use -NotMatch option tho show non matched lines.

Invert Match or Not Match

Count Of Matches

We may need to count the matches. If there are a lot of match counting them one by one is very trivial task. We can use returned matches count property to print count of matched lines.

Count Of Matches

PowerShell: how to grep command output?

In PowerShell I have tried:

This fails even though Alias is clearly in the output. I know this is because select-string is operating on some object and not the actual output string.

What can be done about it?

8 Answers 8

I think this solution is easier and better, use directly the function findstr:

You can also make an alias to use grep word:

Your problem is that alias emits a stream of AliasInfo objects, rather than a stream of strings. This does what I think you want.

or as a function

When you don’t handle things that are in the pipeline (like when you just ran ‘alias’), the shell knows to use the ToString() method on each object (or use the output formats specified in the ETS info).

Читайте также:  Walking past your windows

If you truly want to «grep» the formatted output (display strings) then go with Mike’s approach. There are definitely times where this comes in handy. However if you want to try embracing PowerShell’s object pipeline nature, then try this. First, check out the properties on the objects flowing down the pipeline:

Note the Definition property which is a header you see when you display the output of Get-Alias (alias) e.g.:

Usually the header title matches the property name but not always. That is where using Get-Member comes in handy. It shows you what you need to «script» against. Now if what you want to «grep» is the Definition property contents then consider this. Rather than just grepping that one property’s value, you can instead filter each AliasInfo object in the pipepline by the contents of this property and you can use a regex to do it e.g.:

In this example I use the Where-Object cmdlet to filter objects based on some arbitrary script. In this case, I filter by the Defintion property matched against the regex ‘alias’. Only those objects that return true for that filter are allowed to propagate down the pipeline and get formatted for display on the host.

BTW if you’re typing this, then you can use one of two aliases for Where-Object — ‘Where’ or ‘?’. For example:

PowerShell equivalent to grep -f

I’m looking for the PowerShell equivalent to grep —file=filename . If you don’t know grep , filename is a text file where each line has a regular expression pattern you want to match.

Maybe I’m missing something obvious, but Select-String doesn’t seem to have this option.

9 Answers 9

The -Pattern parameter in Select-String supports an array of patterns. So the one you’re looking for is:

This searches through the textfile doc.txt by using every regex(one per line) in regex.txt

I’m not familiar with grep but with Select-String you can do:

You can also do that with Get-Content:

But essentially it is:

This gives a directory file search (*or you can just specify a file) and a file-content search all in one line of PowerShell, very similar to grep. The output will be similar to:

I had the same issue trying to find text in files with powershell. I used the following — to stay as close to the Linux environment as possible.

Hopefully this helps somebody:

PowerShell:

Explanation:

Yes, this works as well:

This question already has an answer, but I just want to add that in Windows there is Windows Subsystem for Linux WSL.

So for example if you want to check if you have service named Elasicsearch that is in status running you can do something like the snippet below in powershell

net start | grep Elasticsearch

but select-String doesn’t seem to have this option.

Correct. PowerShell is not a clone of *nix shells’ toolset.

However it is not hard to build something like it yourself:

I find out a possible method by «filter» and «alias» of PowerShell, when you want use grep in pipeline output(grep file should be similar):

first define a filter:

then define alias:

final, put the former filter and alias in your profile:

Restart your PS, you can use it:

Profiles(just like .bashrc for bash):enter link description here

out-string(this is the key)enter link description here:in PowerShell Output is object-basedenter link description here,so the key is convert object to string and grep the string.

Select-Stringenter link description here:Finds text in strings and files

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