【问题标题】:Multi-Line String to Single-Line String conversion in PowerShellPowerShell 中的多行字符串到单行字符串的转换
【发布时间】:2017-06-13 02:03:32
【问题描述】:

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

这是一个示例行
这是一个示例行
这是一个示例行

这是另一个示例行
这是另一个示例行
这是另一个示例行

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

这是一个示例行这是一个示例行这是一个示例行

这是另一个示例行这是另一个示例行这是另一个示例行

我对此进行了彻底的研究,并且只找到了将整个文本文件制作成单行的方法。我需要一种方法(最好在循环中)使字符串块数组成为单行。有什么方法可以实现吗?

编辑: 我已经编辑了示例内容以使其更清晰。

【问题讨论】:

    标签: string file powershell text


    【解决方案1】:
    # 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】:

    有点软糖:

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

    这依赖于具有 Windows CRLF 的文件。

    【讨论】:

      【解决方案3】:

      有几种方法可以处理这样的任务。一种是使用正则表达式替换为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()
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-08
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 2016-12-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多