PowerShell中的多行字符串到单行字符串转换

时间:2017-01-27 11:38:58

标签: string file powershell text

我有一个包含多个'块的文本文件。的文字。这些块有多行,并用空行分隔,例如:

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

我需要这些块是单行格式的,例如

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

我对此进行了彻底的研究,并且只找到了将整个文本文件设为单行的方法。我需要一种方法(最好是在一个循环中)制作一个单行的字符串块数组。有没有办法实现这个目标?

编辑: 我编辑了示例内容,使其更清晰。

3 个答案:

答案 0 :(得分:2)

有点软糖:

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

这取决于具有Windows CRLF的文件。

答案 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', ''

答案 2 :(得分:0)

有几种方法来处理这样的任务。一种是使用带有negative lookahead assertion的正则表达式替换:

(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()
    }
}