我的任务是获取类似于下面的文本文件的内容......
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/