2013-02-14 278 views
2

我有一个包含类似的文本文件如下:合并/合并多行成一行从一个文本文件(PowerShell的)

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 

谢谢!

回答

3

试试这个:

$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 

它修剪掉的开始和每行的末尾有额外的空间,并用空格连接所有线路。

+0

这是应用于整个文本文件。如果可能的话,我只想将它应用于大括号之间的文本。 – user2065960 2013-02-14 22:25:58

+0

查看更新的答案。这与您现在回答的其他问题几乎完全相同。 – 2013-02-14 22:52:05

+0

这是一种不同的方法,所以我认为值得提出一个新问题。您的解决方案适用于第一组“Text:{'”。但是它也会改变(修剪和连接)它后面的所有内容。所以它不仅限于整个文件中的大括号之间的文本。我编辑了这个问题,以更好地表示文件内部的内容。我非常感谢你的帮助Graimer。 – user2065960 2013-02-14 23:08:04

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' 

等等,等等,等等...

正文:{字符串1,字符串,STRING3,串,4,STRING5,string6,}

嗒嗒,blah,blah ...

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

+0

不错的解决方案,但这只支持2行。它应该是动态的。 – 2013-02-15 09:54:48

+0

除非我误解了这个问题,这就是目标。它会匹配并替换文本中的任意两行。我会更新答案以更具说明性。 – mjolinor 2013-02-15 14:02:50

+0

他的文件实际上是这样的:http://stackoverflow.com/questions/14840632/powershell-find-and-replace-words-split-by-newline其中有3行。这是一个日志文件或其他东西,所以我猜“文本”部分可以是1行,10行,不时变化 – 2013-02-15 14:13:39