How can I filter filename patterns in PowerShell?

2.8k views Asked by At

I need to do something similar to Unix's ls | grep 'my[rR]egexp?' in Powershell. The similar expression ls | Select-String -Pattern 'my[rR]egexp?' seems to go through contents of the listed files, rather than simply filtering the filenames themselves.

The Select-String documentation hasn't been of much help either.

2

There are 2 answers

3
Joey On BEST ANSWER

Very simple:

ls | where Name -match 'myregex'

There are other options, though:

(ls) -match 'myregex'

Or, depending on how complex your regex is, you could maybe also solve it with a simple wildcard match:

ls wild[ck]ard*.txt

which is faster than above options. And if you can get it into a wildcard match without character classes you can also just use the -Filter parameter to Get-ChildItem (ls), which performs filtering on the file system level and thus is even faster. Note also that PowerShell is case-insensitive by default, so a character class like [rR] is unnecessary.

2
Sundar R On

While researching based on @Joey's answer, I stumbled upon another way to achieve the same (based on Select-String itself):

ls -Name | Select-String -Pattern 'my[Rr]egexp?'

The -Name argument seems to make ls return the result as a plain string rather than FileInfo object, so Select-String treats it as the string to be searched in rather than a list of files to be searched.