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用法。

转载于:https://www.cnblogs.com/aspnetx/archive/2010/06/21/1761753.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值