http://martual.leanote.com/post/Powershell-%E6%9B%BF%E6%8D%A2%E5%A4%9A%E4%B8%AA%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%EF%BC%9Aget-content-replace-set
- 使用
get-childitem获取待处理的文件的集合。 - 对上述集合中的每个文件:
- 加载 - 使用
get-content加载它的内容。 - 替换 - 使用
-replace替换所有的目标字符串。 - 保存 - 通过
set-content存回原文件中。
- 加载 - 使用
- get-childitem "*.txt" | foreach-object { (get-content $_.PSPath) | foreach-object { $_ -replace "oriStr","newStr" } | set-content $_.PSPath }
- get-childitem "*.txt" | foreach-object { (get-content $_.FullName) -replace "oriStr","newStr" | set-content $_.FullName }
在 Powershell 中,可以组合使用
get-childitem , get-content , -replace 和 set-content 这几个命令来替换多个文件中的字符串。
基本思路就是:
示例:
替换当前目录下所有 txt 文件中的 oriStr 为 newStr 。
或者更简单的写法:
需要特别注意的是
get-content 命令周围的括号,它表示该命令执行完才往后继续执行。如果缺少这个括号, set-content 的时候会提示文件被占用(想必你已经猜到是被谁占用了,该问题与 Powershell 中管道的工作机制有关)。此外,PSPath 和 FullName 等价。
没有评论:
发表评论