30

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

3 Answers3

34

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
  • 1,601
  • 14
  • 17
  • Any way to treat the whole file as one string instead of multiples? I.e. to replace line-endings? – Philippe Oct 29 '20 at 12:08
  • `cat`, which is just an alias for `Get-Content` ingest the whole file, and this just goes through each line and do a replace on it. To replace line-ending, do you only care about the last line-ending? or each new paragraphs? – shinjijai Nov 05 '20 at 17:42
  • Why do you think, you need to write it to a file? – Mehrdad Mirreza Sep 27 '22 at 13:39
  • I guess you don't for what the OP wanted. But if you do want to "save" the changes, one way is to write it back to a file. – shinjijai Sep 28 '22 at 14:06
14

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
  • 249
  • 2
  • 3
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.

tammoj
  • 119
  • 4