PowerTip of the Day-Replace Text in Files

原文地址:http://app.en25.com/e/es.aspx?s=1403&e=4615&elq=4e53a85287814a3b889de5a05e61f869

原文:

Often, some text will need to be replaced in a text file. That's easy with Get-Content and Set-Content - or not?

Get-Content c:\somefile.txt | Foreach-Object { $_ -replace 'old', 'new' } | Set-Content c:\somefile.txt

If you try this, PowerShell will complain that the file is in use and can't be written to. PowerShell cannot read and write to a file at the same time. Your solution: use parenthesis so that PowerShell reads the file first and only and then processes the content:

(Get-Content c:\somefile.txt) | Foreach-Object { $_ -replace 'old', 'new' } | Set-Content c:\somefile.txt

 

 

翻译:

经常地,需要替换一个文本文件里的一些文本,使用Get-ContentSet-Content是很简单的:

Get-Content c:\somefile.txt | Foreach-Object { $_ -replace 'old', 'new' } | Set-Content c:\somefile.txt

如果尝试以上代码,PowerShell会提示说文件正在使用不能被写入。PowerShell不能同时读和写一个文件。那么可行的方案是:使用括号,这样PowerShell就会先把文件读出来并且随后处理其内容:

(Get-Content c:\somefile.txt) | Foreach-Object { $_ -replace 'old', 'new' } | Set-Content c:\somefile.txt

 

笔记:

加上括号后powershell会首先完成括号里的任务,相当于提高了优先级。

复习replace用法。

posted @ 2010-06-21 10:25  哥本哈士奇(aspnetx)  阅读(276)  评论(0编辑  收藏  举报