Searching for text in text files or Powershell Grepping

Ask any linux admin and they’ll tell you how useful grep is. Grep is a command in linux allow you go search through piped outputs and/or files for certain strings. Grep also allows for the use for regular expression to search for more complex criterias. For a long time Microsoft users have not have such feature until now with the introduction of Powershell. To search a directory of files for a certain string at the powershell prompt type:

dir | select-string “string to search”

or to use regular expressions:

dir | select-string “regex”

if you just want to look for the filename of the files that contains certain strings and not the strings themselves:

dir prefix*

to comb through all sub-directory of the current directory:

dir -recurse | select-string “string to search”

For further selection or filter of you search, you can pipe the result of the previous pipe:

dir -recurse | select-string “string to search 1” | select-string “string to search 2”

In the example above, it’s the equivalent of saying “Search for the first string, then in the results of the first string search for the second string and ONLY show the output of that”. Kind of like using the AND operant.

Other ways of getting the same results:

select-string -path “c:\text files\*.txt” -pattern “patter to search here” -simplematch -showall

This will only show the objects your searching for, for the line property (showing the whole line) type:

select-string -path “c:\text files\*.txt” -pattern “patter to search here” -simplematch -showall | select line

2 comments

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.