Using -replace on pipes in powershell

12

1

I want to test out a replace before I use it, so I'm trying to write a quick online command to see what the output is. However, I'm not sure what the syntax is. What I want to do is something like

cat file | -replace "a", "b"

What is the correct powershell syntax for this?

I know that I can also do $a = cat file and then do a replace on $a, but I'de like to keep this on one line

David says Reinstate Monica

Posted 2015-04-22T15:09:02.447

Reputation: 952

Answers

15

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

shinjijai

Posted 2015-04-22T15:09:02.447

Reputation: 1 391

4

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

politus

Posted 2015-04-22T15:09:02.447

Reputation: 139