我有一个包含以下内容的文本文件:
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
谢谢!
答案 0 :(得分: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
它会删除每行开头和结尾的多余空格,并用空格连接所有行。
答案 1 :(得分: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,}