加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

unix – 使用powershell替换

发布时间:2020-12-16 01:47:12 所属栏目:安全 来源:网络整理
导读:我想写一个等价的 find -name "*.xml" | xargs grep -l "Search String" | xargs perl -p -i -e 's/Search String/Replace String/g' 在powershell中.这就是我提出的. Get-ChildItem 'D:codecppFileHandlingCppinput - Copy' -Recurse |Select-String -S
我想写一个等价的

find -name "*.xml" | xargs grep -l "Search String" 
       | xargs perl -p -i -e 's/Search String/Replace String/g'

在powershell中.这就是我提出的.

Get-ChildItem 'D:codecppFileHandlingCppinput - Copy' -Recurse |
Select-String -SimpleMatch $src_str | 
foreach{(Get-Content $_.path) | ForEach-Object { $_ -replace $src_str,$target_str }}

我收到错误“进程无法访问该文件,因为它正被另一个进程使用”.所以我想出了多行版本,如下所示.我现在能够替换现在的字符串,除了$src_str.$src_str有什么问题?

$src_str="<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes"" ?>"
$target_str=""
echo $src_str

foreach ($var in (Get-ChildItem 'D:codecppFileHandlingCppinput - Copy' -Recurse 
                     | Select-String -SimpleMatch $src_str).Path) 
{    
  (Get-Content $var) | ForEach-Object { $_ -replace $src_str,$target_str }
    | Set-Content $var    
}

解决方法

也许这将有助于回到实现相当于Unix版本的最初目标.这基本上是等效的PowerShell版本.

$search = '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'
$replace = 'test'
$dir = 'D:codecppFileHandlingCppinput - Copy'

dir -Path $dir -Recurse -Filter *.xml | ForEach-Object {
    (Get-Content -Path $_.FullName) -replace $search,$replace | 
        Set-Content $_.FullName
}

注意 – 注意重写文件时可能发生的文本文件编码更改.如果需要使用Set-Content的-Encoding参数,则可以指定输出编码,例如ASCII.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读