powershell - 如何在powershell中分割文本文件中大于X的行?

标签 powershell split

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

A typical line
A typical line
A line that is 5,000 characters long ...............
A typical line
A line that is 30,000 characters long ......................

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

A typical line
A typical line
A line that is 2056 characters long (max)
A line that is 2056 characters long (max)
A line that is 2056 characters long (max)
A typical line
A line that is 2056 characters long (max)
The rest of that 30,000 char line ... etc.

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

$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 处将它们分开。

A typical line A typical line A line that is 5,000
characters long ............ A Typical line A line that
is 30,000 characters long.

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

最佳答案

获取控制台宽度并在每个 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
}

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

关于powershell - 如何在powershell中分割文本文件中大于X的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51141338/

相关文章:

powershell - 如何将PowerShell输出设置为批处理变量?

电源外壳 : Get-ACL and get permissions for specific user on a remote folder

powershell - 如何从 Powershell 打包 Service Fabric 应用程序?

python - Pandas 按逗号将列拆分为多列

r - 如何分割数据框?

powershell - 创建 subdir 结构,在个位数月份添加零

powershell - Powershell:具有转义参数(-%)的调用运算符(&)无法与非静态参数一起使用

java - 如何在Java中将一个数组列表拆分为多个长度为k的数组列表?我不想查看新列表,但我想创建它们

python - 用 BeautifulSoup 拆分一个元素

java - .split ("|"中的运行时错误)