Replace a string inside a list of files

Reading Time: < 1 minute

Sometimes we need to replace a character string in a flat file.
One possible method could be to use a tool, like notepad++, and open the set of files and use the scan replace options.
But a quick way is again using PowerShell as below:

ls “\cb.n.lo\dfs\reg01\interfaces\T24\From\523.Asn\LU0010001\DOC\NES-TEST\*.xml” -rec | %{ $f=$_; (gc $f.PSPath) | %{ $_ -replace “/Net_Equity_Statement-“, “/NES-” } | sc $f.PSPath }

This will replace the string “/Net_Equity_Statement-” by “/NES” in all *.xml from the directory specified (in my sample it is ” \cb.n.lo\dfs\reg01\interfaces\T24\From\523.Asn\LU0010001\DOC\NES-TEST\”

Here is just another example:
ls *.xml -rec | %{ $f=$_; (gc $f.PSPath) | %{ $_ -replace “<mailingId value=”””, “<mailingId value=””X” } | sc $f.PSPath }

Leave Comment

Your email address will not be published. Required fields are marked *