Using Powershell to search for lines in a text file

I wanted to find all the lines in a log file that contained a specific piece of text. It could have been done with something like Excel, but the text was all in the middle of long strings. So the easiest way was to do it with Powershell.

I started with the following line:

get-content "c:\test.txt" | where {$_ -match "findme"}

That actually worked really well so I built a simple script around it which should work with .txt or .csv files (or even .tsv!).

So here is some simple code to use, which even includes some help information, which can be accessed by running
<

help ./get-txtlines.ps1

Well assuming that you called the file that..

So here is get-txtlines.ps1:

Param ($filepath = "c:\text.txt", $textstr="test", $MatchCount = 0)
$lines = get-content $filepath | where {$_ -match "$textstr"}
If ($MatchCount -eq 1)
{$lines | measure-object}
Else
{$lines}

The file, including the help content can be downloaded here: http://dl.dropbox.com/u/20638386/get-TxtLines.ps1

Advertisements

Leave a comment

Filed under Microsoft, Powershell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s