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

Viewed 321

I have a file like below.

    # 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

I wanted to add line exactly below of caseSensitive: false with 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

I don't know how many lead space of matched string... Leading space may vary depends on file to file.

So my requirement is to add a line exactly below and even consider lead space

NOTE:- I have multi configuration like above and I need add PrinitMatched string on every configuration

1 Answers

Use the -match regular expression operator to test whether the current line consists of leading whitespace followed by the directive you're looking for, then output the required new line right after:

(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"

The regular expression \s* describes "0 or more whitespace characters", and the () parentheses will "capture" the matching string and populate the $Matches variable with it, so this way we can extract the correct number of leading spaces no matter how many.

Related