[英]Powershell- How to wrap a specific line in an array object in double quotes?
假設我有一個文本文件,其內容是:
======= Section 1 ==========
This is line one
This is line two
This is line three
======= Section 2 ==========
This is line Four
This is line Five
This is line Six
我使用$SourceFile = Get-Content '.\source.txt' -Delimiter '==='
將其導入 Powershell 然后使用$Objects = $SourceFile -replace '^=.*', ''
我現在有了這個$Objects
數組具有:
This is line one
This is line two
This is line three
和
This is line Four
This is line Five
This is line Six
我真正想知道的是如何將特定行用雙引號或括號等括起來,以便所有對象數組中的特定行也以相同的方式處理。
例如,兩個數組的第 3 行應該用雙引號括起來:
This is line one
This is line two
"This is line three"
和
This is line Four
This is line Five
"This is line Six"
我嘗試了很多東西,最接近的是$test = $objects -replace 'This is line three', '"This is line three"'
正如你所看到的,這對於許多數組的對象來說並不理想。
我對Powershell還是很陌生,任何幫助將不勝感激
假設您想將每個塊中的第 3 行用雙引號括起來:
# Read the input file and split it into blocks of lines by a
# regex matching the section lines (without including the section lines).
(Get-Content -Raw file.txt) -split '(?m)^===.*\r?\n' -ne '' |
ForEach-Object { # Process each block of lines (multi-line string)
# Split this block into individual lines, ignoring a trailing newline.
$linesInBlock = $_ -replace '\r?\n\z' -split '\r?\n'
# Modify the 3rd line.
$linesInBlock[2] = '"{0}"' -f $linesInBlock[2]
# Output the lines, including the modification.
Write-Verbose -Verbose "-- next block"
$linesInBlock
}
輸出樣本輸入:
VERBOSE: -- next block
This is line one
This is line two
"This is line three"
VERBOSE: -- next block
This is line Four
This is line Five
"This is line Six"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.