使用powershell脚本在文本文件中的特定单词后添加新行

mrwjdhj3  于 2023-03-18  发布在  Shell
关注(0)|答案(2)|浏览(233)

在nginx.conf文件中的单词“server {”后面添加以下行。

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

使用下面的脚本,在单词“server {”出现的任何位置,在该单词旁边添加一个新行。

$Nginx_home = "I:\Anand\nginx-1.22.1"

$filePath = "$Nginx_home\conf\nginx.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

nginx.conf文件包含多个单词“server {"。但是我需要先找到这个单词,然后将下面的行添加到下一行。

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

qq24tv8q1#

使用ForEach-Object检查通过管道的每一行,在您要查找的行后面添加额外的内容:

$Nginx_home = "I:\Anand\nginx-1.22.1"

$filePath = "$Nginx_home\conf\nginx.conf"

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

$content = Get-Content $filePath

$content |ForEach-Object {
  # pass line downstream
  $_
  if ($_ -match '^\s*server\s+\{\s*$'){
    # output the extra stuff if this was the line
    $textToAdd1
  }
} |Set-Content $filePath -Force
u4vypkhs

u4vypkhs2#

我将使用switch来完成此操作,并跟踪您是否已经插入了新文本,以便只插入一次:

$Nginx_home = "I:\Anand\nginx-1.22.1"
$filePath = "$Nginx_home\conf\nginx.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*server\s+{' {
        $_               # 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

相关问题