GREP and SED with PowerShell

 

So...I like GREP and SED from my old UNIX days and am VERY happy to see that PowerShell can do the same type of functionality with a lot more power in most cases. I though some of you might like some really simple examples of how to take a text file and do GREP-ish and SED-ish actions.

 

GREP-ish

cat somefile.txt | where { $_ -match "expression"}

 

The command above will search each line of "somefile.txt" to see if it contains the regular expression "expression" and return the entire line if there is a match.

 

 

 

SED-ish

 

cat somefile.txt | %{$_ -replace "expression","replace"}

 

The command above will search each line of "somefile.txt" for the regular expression "expression" and replace it with the string "replace".

 

 

 

EXAMPLE:

==============DATA.TXT==============

Mary had a little lamb,

It's fleece was white as snow,

But the lamb made Mary mad,

So she ate it.

=================================

 

GREP-ish

cat DATA.TXT | where { $_ -match "Mary"}

 

returns the following:

Mary had a little lamb,

But the lamb made Mary mad,

 

 

SED-ish

cat DATA.TXT | % { $_ -replace "Mary","Susan" }

 

returns the following:

Susan had a little lamb,

It's fleece was white as snow,

But the lamb made Susan mad,

So she ate it.

 

================ Edit 7/14 ==================== 

A question came up the the other day about putting these results into another text file. Using redirection this is quite easy. Here is how it is done:

 

cat DATA.TXT | % { $_ -replace "Mary","Susan" } > newfile.txt

 

============================================

enjoy :)

 

Technorati Tags: regular expressions, grep, sed, match, replace, text file, Mary, little lamb