【问题标题】:how to copy a lines from a file a file after matched string in a file using powershell script如何使用powershell脚本在文件中匹配字符串后从文件中复制行
【发布时间】:2021-10-24 10:39:22
【问题描述】:

我有如下配置 yml 文件..我想在匹配字符串“logs:”后复制所有行直到文件末尾

# numberof Threads
encryptionKey: "abcd"

logs:

  - displayName: "RLM_Failure"
    logDirectory: "/optware/msste/legaluat/log"
    logName: "DSSErrors.log"
    searchStrings:
        #displayName Should be unique across the patterns including the case.
       - displayName: "RLM_Dependency"
         pattern: "Merge fails entirely because needed objects"
         matchExactString: false
         caseSensitive: false

我试过这个命令

Select-String "^logs: "/path/old/config.yml -Context 0, 100 | 
% {$_.Context.PostContext} | 
Add-Content "/path/new/config.yml"

但是这只是在匹配字符串之后处理 100 行......无论如何我可以在不指定行号的情况下实现。

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    将文件逐行读入变量,在SkipUntil模式下使用.Where()扩展方法抓取除logs:之前的行之外的所有内容,然后使用Select-Object -Skip 1跳过logs:行本身:

    $lines = Get-Content /path/old/config.yml
    
    $lines.Where({$_ -match '^\s*logs:\s*(#|$)'}, 'SkipUntil') |Select-Object -Skip 1 |Set-Content /path/new/config.yml
    

    【讨论】:

      【解决方案2】:

      您也可以像这样使用switch

      $outputLine = $false
      $newFile = switch -Regex -File '/path/old/config.yml' {
          '^logs:'  { $outputLine = $true }
          default   { if ($outputLine) { $_ }}
      }
      
      $newFile | Set-Content -Path '/path/new/config.yml'
      

      ((Get-Content -Path '/path/old/config.yml' -Raw) -split '(?m)^logs:', 2)[-1] | 
      Set-Content -Path '/path/new/config.yml'
      

      【讨论】:

        猜你喜欢
        • 2015-06-11
        • 1970-01-01
        • 2012-11-22
        • 1970-01-01
        • 1970-01-01
        • 2020-08-06
        • 1970-01-01
        • 2014-08-11
        • 1970-01-01
        相关资源
        最近更新 更多