Reputation: 67
I got a array which has the value(new line after every "text")
$result=@"
"first","line","of","text"
"second","line","of","text
third","line","of","text"
"fourth","line","of","text"
"@
I am trying to write a powershell code which searches for lines that start with " but does not end with ". If it matches the condition next line is joined to the matched line with a comma delimiter. Ex: second line matches the condition, so third line is joined with the second line with a comma in between. like the one below
"first","line","of","text"
"second","line","of","text,third","line","of","text"
"fourth","line","of","text"
So far I have this with me. But it only adds a , to EOL but does not join it. Please let me know what am I missing
$result=@()
foreach ($item in $result){
if ($item -notlike '*"')
{ $result+=$item+"," }
else
{ $result+=$item}
}
Upvotes: 1
Views: 1909
Reputation: 17462
with multiple replace
$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"
Upvotes: 0
Reputation: 174465
I got a array which has the value(new line after every "text")
$result=@" "first","line","of","text" "second","line","of","text third","line","of","text" "fourth","line","of","text" "@
* (syntax error fixed)
No, you have a multi-line string - there's a difference!
You can use a regular expression pattern to match linebreaks surrounded by optional whitespace, but no "
characters:
$result = $result -replace '(?<!")\s*\r?\n\s*(?!")', ','
The pattern consists of:
(?<!")
- no preceding "
(negative lookbehind assertion)\s*
- 0 or more whitespace characters\r?\n
- line break (CRLF
or LF
)\s*
- 0 or more whitespace characters(?!")
- no following "
(negative lookahead assertion)And finally replaces the thing with a ,
Upvotes: 3
Reputation: 439
I don't know if this is a real XY problem but the question is fuzzy (confusion between a multi-line string and an array for example). Solution from Mathias is fine. However I think the original poster, according to the expected result, missed the correct syntax for the @""@ Here string which is very verbatim: all leading spaces were not intentional. Hence this:
$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
which brings this:
"first","line","of","text"
"second","line","of","text,third","line","of","text"
"fourth","line","of","text"
Upvotes: 0