2017-01-27 11 views
1

テキストの複数の「チャンク」を持つテキストファイルがあります。これらのチャンクは、複数のラインを有しており、空行で分離されている例えば:PowerShellの複数行の文字列から単一行の文字列への変換

This is an example line 
This is an example line 
This is an example line 

This is another example line 
This is another example line 
This is another example line

Iは、例えば、単一のライン形式であるために、これらのチャンクを必要とします

This is an example lineThis is an example lineThis is an example line 

This is another example lineThis is another example lineThis is another example line

私はこれを完全に調査し、テキストファイル全体を1行にする方法しか見つけていません。私は文字列チャンクの配列を単一行にする方法が必要です。これを達成する方法はありますか?

編集: 私は少し内容を明確にするために例のコンテンツを編集しました。

答えて

2
# create a temp file that looks like your content 
# add the A,B,C,etc to each line so we can see them being joined later 
"Axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 
Bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 
Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 

Dxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 
Exxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 
Fxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 

Gxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 
Hxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 
Ixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" | Set-Content -Path "$($env:TEMP)\JoinChunks.txt" 

# read the file content as one big chunk of text (rather than an array of lines 
$textChunk = Get-Content -Path "$($env:TEMP)\JoinChunks.txt" -Raw 

# split the text into an array of lines 
# the regex "(\r*\n){2,}" means 'split the whole text into an array where there are two or more linefeeds 
$chunksToJoin = $textChunk -split "(\r*\n){2,}" 

# remove linefeeds for each section and output the contents 
$chunksToJoin -replace '\r*\n', '' 

# one line equivalent of above 
((Get-Content -Path "$($env:TEMP)\JoinChunks.txt" -Raw) -split "(\r*\n){2,}") -replace '\r*\n', '' 
+0

パーフェクト一つはnegative lookahead assertionと、正規表現の置換を使用することです。どうもありがとう! – AJennings1

2

ファッジのビット:

[String] $strText = [System.IO.File]::ReadAllText( "c:\temp\test.txt"); 
[String[]] $arrLines = ($strText -split "`r`n`r`n").replace("`r`n", ""); 

これは、WindowsのCRLFを持つファイルに依存しています。

0

このようなタスクにはいくつかの方法があります。

(Get-Content 'C:\path\to\input.txt' | Out-String) -replace "`r?`n(?!`r?`n)" | 
    Set-Content 'C:\path\to\output.txt' 

あなたはまたStreamReaderStreamWriterで仕事ができる:

$reader = New-Object IO.StreamReader 'C:\path\to\input.txt' 
$writer = New-Object IO.StreamWriter 'C:\path\to\output.txt' 

while ($reader.Peek() -gt 0) { 
    $line = $reader.ReadLine() 
    if ($line.Trim() -ne '') { 
     $writer.Write($line) 
    } else { 
     $writer.WriteLine() 
    } 
}