The Computer Oracle

Using -replace on pipes in powershell

--------------------------------------------------
Become or hire the top 3% of the developers on Toptal https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Music Box Puzzles

--

Chapters
00:00 Question
00:39 Accepted answer (Score 36)
00:59 Answer 2 (Score 16)
01:32 Answer 3 (Score 1)
02:41 Thank you

--

Full question
https://superuser.com/questions/904741/u...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#powershell #findandreplace #pipe #cat

#avk47



ACCEPTED ANSWER

Score 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



ANSWER 2

Score 16


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



ANSWER 3

Score 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.