user2065960
user2065960

Reputation: 45

Combine/Merge Multiple Lines into One Line from a Text File (Powershell)

I have a text file that contains something like the following:

blah, blah, blah ...

Text : {string1, string2, string3,
        string4, string5, string6,}

blah, blah, blah ...

Text : {string7, string8, string9,
        string10, string11, string12,}

and I would like to merge only the lines between the braces into one line to look like this:

blah, blah, blah ...

Text : {string1, string2, string3, string4, string5, string6,}

blah, blah, blah ...

Text : {string7, string8, string9, string10, string11, string12,}

However, I don't want to apply the change to the entire text file because it contains other things. I would like to edit only the text between braces { ... }. I messed around with -join but couldn't get it to work. I have the following script which opens the file, makes changes, and output into another file:

gc input.txt | 

# Here I have several editing commands, like find/replace.
# It would be great if I could add the new change here.

sc output.txt

Thank you!

Upvotes: 2

Views: 18626

Answers (2)

mjolinor
mjolinor

Reputation: 68273

Jumbo shrimp in a can:

$testdata = @'
blah, blah, blah ...

Text : {string1, string2, string3,
        string4, string5, string6,}

blah, blah, blah ...

Text : {string7, string8, string9,
        string10, string11, string12,}
'@

$testfile = 'c:\testfiles\testfile.txt'
$testdata | sc $testfile
$text = [IO.File]::ReadAllText($testfile)

$regex = @'
(?ms)(Text\s*:\s\{[^}]+)\s*
\s*([^}]+)\s*
'@

$text -replace $regex,'$1 $2'

blah, blah, blah ...

Text : {string1, string2, string3, string4, string5, string6,}

blah, blah, blah ...

Text : {string7, string8, string9, string10, string11, string12,}

Upvotes: 1

Frode F.
Frode F.

Reputation: 54881

Try this:

$text = (Get-Content .\input.txt) -join "`r`n"
($text | Select-String '(?s)(?<=Text : \{)(.+?)(?=\})' -AllMatches).Matches | % {
        $text = $text.Replace($_.Value, ($_.Value -split "`r`n" | % { $_.Trim() }) -join " ")
}
$text | Set-Content output.txt

It trims away the extra spaces at the start and end of each line, and connects all lines with a space.

Upvotes: 4

Related Questions