【问题标题】:How to split a text file's lines greater than X in powershell?如何在powershell中拆分大于X的文本文件行?
【发布时间】:2018-07-04 00:16:28
【问题描述】:

我的任务是获取类似于下面的文本文件的内容...

典型线路
典型线路
5,000 个字符长的行 ....................
典型线路
一行长度为 30,000 个字符 ....................

并在 $x 个字符处分割极长的行(可能是 2056),所以它看起来像......

典型线路
典型线路
一行长度为 2056 个字符(最大值)
一行长度为 2056 个字符(最大值)
一行长度为 2056 个字符(最大值)
典型线路
一行长度为 2056 个字符(最大值)
剩下的 30,000 个字符行……等等。

我不知道我在做什么,这是我最好的猜测:

$originalfile = "C:\test\file.txt"
$output = "C:\test\output.txt"

foreach($line in Get-Content $originalfile){
    if ($line.length -gt 2056){
        $line -split ... ???
    } else {
        $line | out-file -Append $output
    }
}

我尝试了我发现的这个例子:

(Get-Content $originalfile) -join " " -split '(.{2056,}?[ |$])' | Where-Object{$_} | out-file $output

...但我永远无法让输出正常工作,它只是将它放在一个长字符串中,但它确实在 2056 年将它们分开。

典型线路 典型线路 5,000 线路
字符长............ A 典型行 A line that
长度为 30,000 个字符。

在一个完美的世界中,我会尝试在一个空间上进行拆分,但是经过两天的谷歌搜索,我基本上已经放弃了,并且不在乎它是否将单词分成两半。

【问题讨论】:

  • 所以你要实现自动换行?
  • 肯定不是骗人的。用户正在尝试包装文本文件的内容。不是 cmdlet 输出。我想你可以从答案中获取一些概念来为这个问题找到一个可行的答案,但这个问题本身并不是一个骗局。\
  • 文本文件可能包含多字节 unicode 字符(例如 UTF-8)。一些多字节字符可能放在 2056 和 2057 字节上。它不应该破坏字符。我认为它需要修改你的任务。

标签: powershell split


【解决方案1】:

获取控制台宽度并每隔width 个字符添加一个换行符(这不考虑空格):

# Really long string from whatever command
$mySuperLongOutputString = "SOMETHING REALLY LONG, LONGER THAN THIS"

# Get the current console width
$consoleWidth = $Host.UI.RawUI.WindowSize.Width

# For loop to iterate over each intended line in the string
for( $i = $consoleWidth; $i -lt $mySuperLongOutputString.Length; $i += $consoleWidth ) {
  # Insert string at the end of the console output
  $mySuperLongOutputString = $mySuperLongOutputString.Insert( $i, "`r`n" )

  # Bump the counter by two to skip counting the additional newline characters
  $i += 2
}

控制台宽度等于缓冲区宽度的列数。

【讨论】:

    【解决方案2】:

    我确实最终让这个工作(大部分)。它确实拆分了一行中的第一个单词,但我可能只需要稍微调整一下正则表达式。

    foreach($line in Get-Content $originalfile){
        if ($line.length -gt 2056){
            $linearray = [regex]::split($line, '(.{2000}\s)') 
            for ($i=0; $i -lt $linearray.length; $i++) {
                $linearray[$i] | out-file -Append $output
            }
            $linearray=@()
        } else {
            $line | out-file -Append $output
        }
    }
    

    抱歉,我一开始就没有很好地解释这个问题,我的大脑不适合这种东西。 谢谢 Bender 的回答,虽然我无法让它工作。我猜是因为文本文件在一个数组中(.insert 对我不起作用),但它确实让我朝着不同的方向进行研究。

    【讨论】:

    • 我的回答确实假设您的文本是单个字符串,而不是数组。这可以通过Get-Content 来实现,尽管使用$text = Get-Content $filename | Out-String。但我很高兴我的回答为您找到了适合您的场景的解决方案,IMO 比简单地使用另一个用户的答案更好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 2019-05-02
    相关资源
    最近更新 更多