【问题标题】:How to use this command with PowerShell?如何在 PowerShell 中使用此命令?
【发布时间】:2013-12-06 11:21:47
【问题描述】:

我需要对一个包含大约 3000 个文档的库运行以下命令,但一直无法获得一个有效的正则表达式(不是我最擅长的),或者相当于 PowerShell 中的 /v 选项。有人可以指出我正确的方向吗?

我的命令

C:\findstr /v "<?xml version=" filename.htm > ..\testOut\filename.htm

到目前为止我使用 PowerShell 的情况

(Get-Content ($srcfiles)) | Foreach-Object {$_.srcfiles -replace '<?xml version="1.0" encoding="utf-8"?>', ("")} | Set-Content  ($srcfiles)

【问题讨论】:

    标签: windows powershell replace


    【解决方案1】:

    Get-Content 返回一个行数组,而不是作为单个字符串的文件全文。

    如果您正在尝试从每个文件中删除 xml 声明,请尝试此操作,假设 $srcfiles 是完整文件路径的集合:

    foreach($file in $srcfiles)
    {
        $content = Get-Content $file | ? { $_ -notmatch "<\?xml[^>]+>" }
        $content | Set-Content $file -Force
    }
    

    基本上,遍历所有文件,获取每个文件的内容,忽略任何 xml 声明行,然后将该数据推送回原始文件。我分两步执行此操作,因为 PowerShell 不会让您将内容写入您正在获取数据的同一管道中的文件。

    【讨论】:

      【解决方案2】:
      $path = "C:\Path\To\Documents"
      $outputPath = "C:\Path\To\OutputDocuments"
      
      Get-ChildItem $path | % { 
         $content = ( Get-Content -Raw $_ ) -replace '<?xml version="1.0" encoding="utf-8"?>', '' 
         $fileName = Join-Path $outputPath $_.Name
         Set-Content -Path $fileName -Value $content
      }
      

      如果您使用的是 PowerShell 2.0 或更低版本,请将“Get-Content -Raw”替换为“Get-Content -ReadCount 0”。

      您还需要过滤 Get-ChildItem 的输出以仅返回文件,而不是目录。在 PowerShell 3.0 或更高版本中,您可以将“-File”参数添加到 Get-ChildItem。否则,试试这个:

      Get-ChildItem $path | ? { $_.GetType() -eq "FileInfo" } | % {
      

      【讨论】:

        猜你喜欢
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        相关资源
        最近更新 更多