如何在电源外壳中拆分文本文件大于 X 的行?



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

一行典型行 一行



典型行 一行长 5,000 个字符...............
一行典型的行
30,000 个字符长的行......

并将$x个字符(可能是 2056 个字符(的极长线条分开,所以它看起来像......

一行典型行 一行 2056 个字符长(最多(一行 2056 个字符长(最多(一行 2056 个字符长(最多(一行典型行 2056 个字符长(最多






(一行
2056 个字符长(最多(
这 30,000 个字符行的其余部分...等。

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

$originalfile = "C:testfile.txt"
$output = "C:testoutput.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 年将它们分开。

一行典型行

一行典型行 5000
个字符长的行......典型行 长度为 30,000 个字符的
行。

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

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

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

我最终确实让它工作(大部分(。 它确实在一行中拆分了一点第一个单词,但我可能只需要对正则表达式进行更多调整。

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

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

最新更新