简体   繁体   English

Powershell-如何用双引号将数组对象中的特定行括起来?

[英]Powershell- How to wrap a specific line in an array object in double quotes?

Lets say I have a text file whose content is this:假设我有一个文本文件,其内容是:

======= 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

I import it into Powershell using $SourceFile = Get-Content '.\source.txt' -Delimiter '===' then clean it up with $Objects = $SourceFile -replace '^=.*', '' I now have this $Objects array that has:我使用$SourceFile = Get-Content '.\source.txt' -Delimiter '==='将其导入 Powershell 然后使用$Objects = $SourceFile -replace '^=.*', ''我现在有了这个$Objects数组具有:

This is line one
This is line two
This is line three

and

This is line Four
This is line Five
This is line Six

What I really want to know is how can I wrap a specific line in double quotes or parenthesis etc, so that specific line in all the objects arrays are also handled the same way.我真正想知道的是如何将特定行用双引号或括号等括起来,以便所有对象数组中的特定行也以相同的方式处理。

For example line 3 of both arrays should have double quotes wrapped around them:例如,两个数组的第 3 行应该用双引号括起来:

This is line one
This is line two
"This is line three"

and

This is line Four
This is line Five
"This is line Six"

I have tried many things, closest I got was $test = $objects -replace 'This is line three', '"This is line three"' As you can see this is less than ideal for an object of many arrays.我尝试了很多东西,最接近的是$test = $objects -replace 'This is line three', '"This is line three"'正如你所看到的,这对于许多数组的对象来说并不理想。

I am still fairly new to Powershell, any help would be greatly appreciated我对Powershell还是很陌生,任何帮助将不胜感激

Assuming that you want to wrap the 3rd line in each block in double quotes:假设您想将每个块中的第 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
  }

Output with your sample input:输出样本输入:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM