html tool

2017年12月19日星期二

powershell 中文件字符串替换


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

    在 Powershell 中,可以组合使用 get-childitem , get-content , -replace 和 set-content 这几个命令来替换多个文件中的字符串。

    基本思路就是:
    1. 使用 get-childitem 获取待处理的文件的集合。
    2. 对上述集合中的每个文件:
      1. 加载 - 使用 get-content 加载它的内容。
      2. 替换 - 使用 -replace 替换所有的目标字符串。
      3. 保存 - 通过 set-content 存回原文件中。

    示例:

    替换当前目录下所有 txt 文件中的 oriStr 为 newStr 。
    1. get-childitem "*.txt" | foreach-object { (get-content $_.PSPath) | foreach-object { $_ -replace "oriStr","newStr" } | set-content $_.PSPath }
    或者更简单的写法:
    1. get-childitem "*.txt" | foreach-object { (get-content $_.FullName) -replace "oriStr","newStr" | set-content $_.FullName }
    需要特别注意的是 get-content 命令周围的括号,它表示该命令执行完才往后继续执行。如果缺少这个括号, set-content 的时候会提示文件被占用(想必你已经猜到是被谁占用了,该问题与 Powershell 中管道的工作机制有关)。此外,PSPath 和 FullName 等价。

没有评论:

发表评论