skip to Main Content

Add the below line after the word "server {" in nginx.conf file.


 location /nginx-status {
 stub_status on;
 allow all;
 }

Using the script below adds a new line next to the word "server {" wherever that word occurs.

$Nginx_home = "I:Anandnginx-1.22.1"

$filePath = "$Nginx_homeconfnginx.conf"

$textToAdd1 = {
     location /nginx-status {
     stub_status on;
     allow all;
     }
}

$content = Get-Content $filePath
# Replace the specific word with the word followed by a new line character
$content = $content -replace "server {", "server {`n$textToAdd1"

# Write the updated contents back to the text file
Set-Content $filePath $content

The nginx.conf file contains more than one word "server {". But I need to find the word first and add the below lines to the next line.


 location /nginx-status {
 stub_status on;
 allow all;
 }

2

Answers


  1. Use the ForEach-Object to inspect each line as it passes through the pipeline, add the extra content after the line you’re looking for:

    $Nginx_home = "I:Anandnginx-1.22.1"
    
    $filePath = "$Nginx_homeconfnginx.conf"
    
    $textToAdd1 = @'
         location /nginx-status {
         stub_status on;
         allow all;
         }
    '@
    
    $content = Get-Content $filePath
    
    $content |ForEach-Object {
      # pass line downstream
      $_
      if ($_ -match '^s*servers+{s*$'){
        # output the extra stuff if this was the line
        $textToAdd1
      }
    } |Set-Content $filePath -Force
    
    Login or Signup to reply.
  2. I would use switch for this and keep track if you have already inserted the new text in order to only do that once:

    $Nginx_home = "I:Anandnginx-1.22.1"
    $filePath = "$Nginx_homeconfnginx.conf"
    # a Here-String for the added text
    $textToAdd1 = @'
         location /nginx-status {
           stub_status on;
           allow all;
         }
    '@
    
    $added = $false
    $newContent = switch -Regex -File $filePath {
        '^s*servers+{' {
            $_               # output this line
            if (!$added) {
                $textToAdd1  # output the text to insert
                $added = $true
            }
        }
        default { $_ }
    }
    
    # Write the updated contents back to the text file
    $newContent | Set-Content -Path $filePath
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search