The Computer Oracle

Using -replace on pipes in powershell

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping

--

Chapters
00:00 Using -Replace On Pipes In Powershell
00:26 Accepted Answer Score 38
00:42 Answer 2 Score 16
01:07 Answer 3 Score 1
01:50 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.