添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

I have a text file that after 80 characters per line pushes the remaining characters to the next line. So I'd like to see how I can create a logic that allows me to capture the next 48 characters from the following line only when there is 80 characters in the first line.

Example (Note: Stack only allows 76 characters per line, but same idea)

Sample File:

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

So basically my variable would hold the following:

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

This is my current code that started the logic:

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

Thanks

During your loop you should be able to count each character and push it into whatever variable is needed. Your code right now is only going to tell you if a line has 80 characters in it. – Jason Snell Aug 31 '17 at 21:45

For anyone curious... I was able to accomplish it by using the following code:

$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++
        
            
                    improve this answer
                You may want to look into using a for loop instead of a foreach loop for this. With a for loop you are increasing a variable number each time so you know exactly where the loop is. You don't have to have an outside variable like $lineNumber counting up for you.
                    – Jason Snell
                Aug 31 '17 at 22:06
                One other thing is you may have an issue with duplicated text if you have two lines that are both 80 characters following each other.
                    – Jason Snell
                Aug 31 '17 at 22:08
                Hi Jason, good idea about the For Loop vs. ForEach. Regarding your second comment, I know for a fact I won't have 2 consecutive lines with 80 characters each...but yeah, that would have been a problem! Thx
                    – Awsmike
                Aug 31 '17 at 22:11