2017-08-31 103 views
0

我有一个文本文件,每行80个字符后将其余字符推送到下一行。所以我想看看如何创建一个逻辑,只有当第一行有80个字符时,我才能从下一行捕获下一个48个字符。Powershell:从下一行抓取字符,直到特定数量的字符

例子(注:堆栈只允许每行76个字符,但同样的想法)

示例文件:

This is a test where I would like this entire line and everything that will 
be g 
oing to this line up until character 48.     08/31/2017 

所以基本上我的变量将举行以下:

This is a test where I would like this entire line and everything that will 
be going to this line up until character 48. 

这是我现在的代码启动逻辑:

$lineArray = Get-Content "c:\sample.txt" 
ForEach ($line in $lineArray) 
If ($line.length -eq 80) {Write-Host $line.length " - Max characters 
Reached"} 
else {Write-Host $line.length " - Within Limits"} 
} 

感谢

+0

在你的循环,你应该可以算每个字符并将其推入任何变量需要。你的代码现在只会告诉你一行是否有80个字符。 –

回答

0

对于任何人好奇......我是能够通过使用下面的代码来完成它:

$lineArray = Get-Content "C:\sample.txt" 
$lineNumber = 0 

ForEach ($line in $lineArray) 
{#Write-Host $line.length 

    If ($line.length -eq 80) 
    {#Write-Host $line.length " - Max characters Reached" 
    $nextLine = $lineArray[$lineNumber +1] 
    $retrieve48 = $nextLine.substring(0,48) 
    $newLine = $line + $retrieve48 
    Write-Host = $newLine 
    } 
    else {Write-Host $line.length " - Within Limits"} 
    $lineNumber++ 
    } 
+1

您可能想要考虑使用for循环而不是foreach循环来实现此目的。使用for循环,您每次都会增加一个可变数字,以便您确切知道循环的位置。你不必像'$ lineNumber'那样有一个外部变量为你计算。 –

+0

另一件事是,如果您有两行都是80个字符,则可能会出现重复文本问题。 –

+0

嗨贾森,关于For Loop vs. ForEach的好主意。关于你的第二个评论,我知道一个事实,我不会有连续的两行,每行80个字符......但是,这将是一个问题!谢谢 – Awsmike

相关问题