Regular expression for validating numbers in asp net dating for greeks
Select-String treats text as most commands in Power Shell do, as an array of chars, and it also processes one line at the time.
Because of this, we have to be a little clever to re-create this example in Power Shell: I admit this looks a bit nasty compared to the grep equivalent, but it’s all due to the differences of the two commands (as described above).
Let’s see what I had to do to get the same results as grep. As you have seen already, Select-String shows the line numbers (as well as the file name) by default, but the following command can be used if you want to only show the line numbers and the matching line: Note that some of the examples I have shown in Power Shell are not the best way of using Select-String (for example the above example), but I included it to show that it’s possible to mimic the output you get from grep.
First I use Get-Content (alias gc) with a read-count of 0, which tells Power Shell to send all lines through the pipeline at the same time. It’s important to take advantage of the fact that you are working with objects when doing stuff in Power Shell, since you never know when you might want to do something besides show the results to the screen, like output to another command for further processing, or saving it to a file.
Select-String is then run on what it got through the pipeline and performs the matching. To illustrate the point I’m going to re-do the above example the “Power Shell way”.
We then utilize the matches property of the returned object, use For Each-Object to iterate through the matches and concatenate our string using the Index and Value properties of the Match Info object. The first command runs Select-String, then I pipe the results to Select-Object because I only want to select the Line Number and Line properties.
In this example it’s used together with the -o parameter we looked at in the last example, as well as a new test-file.
Since grep treats text as “just” text, what you see above is the index of the match as grep reads the whole text in one chunk.
It is possible to do this, but you would have to create a custom function for it.
We just have to use Select-Object to tell Power Shell that we want it.
In this case, we are using -Unique since we just need the different file names displayed once, and -Expand Property so that we don’t get the property header.
I recently ran across an article about ‘15 Practical Grep Command Examples In Linux/Unix‘, and thought it would be cool to run through each of the examples, and give the Power Shell equivalent for each one.
In Power Shell, the command used for string matching is of course Select-String, but since these examples are meant to be run in the console, I will be using the default alias ‘sls‘.