2013-02-14 101 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