2

我有一个包含以下内容的文本文件:

blah, blah, blah ...

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

blah, blah, blah ...

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

我想只将大括号之间的行合并为一行,如下所示:

blah, blah, blah ...

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

blah, blah, blah ...

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

但是,我不想将更改应用于整个文本文件,因为它包含其他内容。我只想编辑大括号 { ... } 之间的文本。我搞砸了,-join但无法让它工作。我有以下脚本可以打开文件、进行更改并输出到另一个文件中:

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

谢谢!

4

2 回答 2

4

试试这个:

$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

它修剪掉每行开头和结尾的多余空格,并用空格连接所有行。

于 2013-02-14T21:58:47.970 回答
1

罐装大虾:

$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'

等等等等等等 ...

文本:{string1,string2,string3,string4,string5,string6,}

等等等等等等 ...

文本:{string7,string8,string9,string10,string11,string12,}

于 2013-02-15T07:39:31.223 回答