Using -replace on pipes in powershell

Solution 1:

This should do the trick, it'll go through all the lines in the file, and replace any "a" with "b", but you'll need to save that back into a file afterwards

cat file | % {$_.replace("a","b")} | out-file newfile

Solution 2:

To use the Powershell -replace operator (which works with regular expressions) do this:

cat file.txt | % {$_ -replace "\W", ""} # -replace operator uses regex

note that the -replace operator uses regex matching, whereas the following example would use a non-regex text find and replace, as it uses the String.Replace method of the .NET Framework

cat file | % {$_.replace("abc","def")} # string.Replace uses text matching