33

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

0

3 Answers 3

37

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
4
  • Any way to treat the whole file as one string instead of multiples? I.e. to replace line-endings?
    – Philippe
    Oct 29, 2020 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 5, 2020 at 17:42
  • Why do you think, you need to write it to a file? Sep 27, 2022 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, 2022 at 14:06
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
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.

2
  • You also may use an regexp: %{$_ -replace("\\", "/")}.
    – tammoj
    Jul 8, 2020 at 15:22
  • off-topic and adds no new information Sep 27, 2022 at 13:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .