Powershell:在数组中连接两行

时间:2016-11-08 14:10:45

标签: powershell

我得到了一个具有值的数组(每个“text”之后的新行)

$result=@"
        "first","line","of","text"
        "second","line","of","text
        third","line","of","text"
        "fourth","line","of","text"
       "@

我正在尝试编写一个powershell代码,用于搜索以“但不以...结尾”开头的行。如果匹配条件,则下一行使用逗号分隔符连接到匹配的行。例如:第二行与条件匹配,因此第三行与第二行连接,中间使用逗号。喜欢下面的那个

"first","line","of","text"
"second","line","of","text,third","line","of","text"
"fourth","line","of","text"

到目前为止,我和我有这个。但它只为EOL添加了一个,但没有加入它。请让我知道我错过了什么

$result=@()
foreach ($item in $result){
if ($item -notlike '*"') 
{ $result+=$item+"," } 
else
{ $result+=$item}
}

3 个答案:

答案 0 :(得分:3)

  

我得到了一个具有值的数组(每个&#34之后的新行;文本")

$result=@"
        "first","line","of","text"
        "second","line","of","text
        third","line","of","text"
        "fourth","line","of","text"
"@
     

* (语法错误已修复)

不,你有一个多行字符串 - 这有区别!

您可以使用正则表达式模式来匹配可选空格所包围的换行符,但不包含"个字符:

$result = $result -replace '(?<!")\s*\r?\n\s*(?!")', ','

该模式包括:

  • (?<!") - 没有先前的"(负面的背后断言)
  • \s* - 0个或更多空格字符
  • \r?\n - 换行符(CRLFLF
  • \s* - 0个或更多空格字符
  • (?!") - 没有关注"(负面前瞻断言)

最后用,

替换该东西

答案 1 :(得分:0)

我不知道这是否是一个真正的 XY问题,但问题是模糊的(例如,多行字符串和数组之间的混淆)。 Mathias的解决方案很好。但是我认为根据预期的结果,原始海报错过了@&#34;&#34; @ Here 字符串的正确语法, 非常逐字 em> :所有前导空格都是故意。因此:

$result=@"
"first","line","of","text"
"second","line","of","text
third","line","of","text"
"fourth","line","of","text"
"@
$result=$result -replace '(?<!")\r?\n(?!")', ','
write-output $result

带来了这个:

"first","line","of","text"
"second","line","of","text,third","line","of","text"
"fourth","line","of","text"

答案 2 :(得分:0)

多次替换

$result=@"
"first","line","of","text"
"second","line","of","text
third","line","of","text"
"fourth","line","of","text"
"@

(((($result -split "`n") -join """ ") -replace """ """, """`n""") -replace """ ", " ") -replace "\""`n", "`n"