查找具有前导 space 的字符串并在正下方添加行以在 windows 中添加行

Find a string which has leading space and add line exactly below to add line in windows

我有一个如下所示的文件。

    # Start OF Java_Out_Of_Memory
    - displayName: "Java_Out_Of_Memory"
      logDirectory: "/opt/xyz"
      logName: "TextLog_*"
      searchStrings:
         - displayName: "Out_Of_Memory"
           pattern: "java.lang.OutOfMemoryError"
           matchExactString: false
           caseSensitive: false 
    # End OF Java_Out_Of_Memory

我想在 caseSensitive: false 的正下方添加一行 printMatchesString: false...

# Start OF Java_Out_Of_Memory
    - displayName: "Java_Out_Of_Memory"
      logDirectory: "/opt/xyz"
      logName: "TextLog_*"
      searchStrings:
          #displayName Should be unique across the patterns including the case.
         - displayName: "Out_Of_Memory"
           pattern: "java.lang.OutOfMemoryError"
           matchExactString: false
           caseSensitive: false  
           printMatchedString: false
# End OF Java_Out_Of_Memory

我不知道匹配的字符串有多少前导 space...前导 space 可能因文件而异。

所以我的要求是在正下方添加一行甚至考虑引导space

注意:- 我有多个配置,如上,我需要在每个配置上添加 PrinitMatched 字符串

使用 -match 正则表达式运算符来测试当前行是否由前导空格和后跟您要查找的指令组成,然后在之后输出所需的新行:

(Get-Content "path\to\input\file.yml") |ForEach-Object {
  # output current line as-is
  $_

  # test if current line is the `caseSensitive` directive:
  if($_ -match '^(\s*)caseSensitive: false\s*$'){
    # use the $Matches automatic variable to extract the leading whitespace
    $leadingSpace = $Matches[1]

    # output new directive with correct leading space
    "${leadingSpace}printMatchedString: false"
  }
} |Set-Content "path\to\output\file.yml"

正则表达式\s*描述“0个或多个空白字符”,()括号将“捕获”匹配的字符串并用它填充$Matches变量,所以这样我们就可以提取正确数量的前导空格,不管有多少。