0

So I was trying to do some simple text manipulation. I found that when just writing to a file of a different name using the code below it works fine:

PS C:\Users\uzfm> Get-Content .\pathSystem.txt | %{$_ -replace ";","`r`n"} > .\pathSystem1.txt

But if I try to just overwrite to the original file like such:

PS C:\Users\uzfm> Get-Content .\pathSystem.txt | %{$_ -replace ";","`r`n"} > .\pathSystem.txt

The command is stuck in an infinite loop and I am just trying to understand the underlying reason as to this functionality when trying to overwrite the file.

If there is a way that works that would be appreciated also.

  • what is the content of the pathsystem.txt file. Could you please provide a sample – Ranadip Dutta Feb 24 '17 at 18:23
  • it is literally just a csv text file of the path variable. i.e.) C:\Sybase32\DBISQL\bin;C:\Sybase32\DataAccess\ADONET\dll;C:\Sybase32\DataAccess\OLEDB\dll;C:\Sybase32\OCS-15_0\lib3p;C:\Sybase32\OCS-15_0\dll;C:\Sybase32\OCS-15_0\bin;C:\Sybase64\DBISQL\bin;C:\Sybase64\DataAccess64\ADONET\dll;C:\Sybase64\DataAccess\ADONET\dll;C:\Sybase64\DataAccess64\ODBC\dll;C:\Sybase64\DataAccess\ODBC\dll;C:\Sybase64\DataAccess64\OLEDB\dll;C:\Sybase64\DataAccess\OLEDB\dll; – labowski2944 Feb 24 '17 at 18:25
  • [Powershell's out-file clears the file when piped from itself](//stackoverflow.com/q/42445471) is basically an identical question. Simply enclose the first part in parentheses. – wOxxOm Feb 24 '17 at 18:29
  • On UNIX systems -- and I'd be surprised if PowerShell were any different in this respect -- a pipeline is executed in parallel, everything happening at the same time. Thus, the output redirection happens when the pipeline is **started**, not when it's complete, so `Get-Content` is trying to read from the same file that results are being written to -- hence your loop. For behavior to be otherwise, you'd need to add buffering and lose parallelization (and also lose the ability to monitor contents as they're written over time), which is why changing this semantic would have expensive tradeoffs. – Charles Duffy Feb 24 '17 at 18:30
  • thanks for the link wOxxOm – labowski2944 Feb 24 '17 at 18:37

1 Answers1

0

try to add parenthèses, execution read all and ended can write into same file, like this

(Get-Content .\pathSystem.txt | %{$_ -replace ";","`r`n"}) > .\pathSystem.txt

or like this :

(Get-Content .\pathSystem.txt) -replace ";","`r`n" > .\pathSystem.txt
Esperento57
  • 16,521
  • 3
  • 39
  • 45