Powershell:从下一行抓取字符直到特定数量的字符

时间:2017-08-31 21:33:07

标签: powershell scripting

我有一个文本文件,每行80个字符后将剩余的字符推送到下一行。因此,我想看看如何创建一个逻辑,只有当第一行中有80个字符时,才允许我从下一行捕获接下来的48个字符。

示例(注意:堆栈每行只允许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"} 
 }

谢谢

1 个答案:

答案 0 :(得分: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++
  }