34

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

4 Answers4

38

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 | foreach {$_.replace("a","b")} | out-file newfile
Dennis
  • 163
shinjijai
  • 1,651
17

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

cat file.txt | foreach {$_ -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 | foreach {$_.replace("abc","def")} # string.Replace uses text matching
Dennis
  • 163
politus
  • 279
2

If you prefer to stick to plain Powershell:

$(cat file) -replace "a","b" | out-file newfile

Which is equivalent to shinjijai's answer:

cat file | foreach {$_.replace("a","b")} | out-file newfile
c z
  • 139
1

I want to add the possibility to use the above mentioned solution as input for command pipes which require slashes instead of backslashes.

I hit this while using jest under Windows, whereby jest requires slashes and Windows path autocompletion returns backslashes:

.\jest.cmd .\path\to\test  <== Error; jest requires "/"

Instead I use:

.\jest.cmd (echo .\path\to\test | %{$_ -replace "\\", "/"})

which results to

.\jest.cmd ./path/to/test

Even multiple paths could be "transformed" by using an array (echo path1, path2, path3 | ...). For example to specify also a config file I use:

.\jest.cmd --config (echo .\path\to\config, .\path\to\test | %{$_.replace("\", "/")})

.\jest.cmd --config ./path/to/config ./path/to/test

The nice thing is that you still could use the native path autocompletion to navigate to your files.

tammo
  • 119