Reputation: 91
We have reports where we need to reformat certain lines of text within each record (currently being done manually), however, they come in one large text file. Each record can be anywhere from 64 - 70 lines in length, but it will be one record per page when printed, so we need to know how long each one is so they can be properly formatted and written to a new file.
Since each record starts and ends with keywords, we can count the number of lines between them to know how many lines we're dealing with, but how do we start reading from that position?
For example, the first record starts at line 72 and is 68 lines long. So the next record will start at 145 (68 lines, plus footer keywords and empty lines). How do we start at line 145 and then read 'x' number of lines?
I was think of a Do/While or Do/Until, but that doesn't seem to be working. I use Do/Until and it's either returning empty lines or it's repeating a single line over and over. Plus, it doesn't help with starting to read the file from a specific line.
$path = "\somefolder\somefile.txt"
$array = @()
$linecount = 0
#Read the file; this is the Header section
#Number of lines may vary
foreach($line in Get-Content $path)
{
$linecount++
If($line -match "End of Header")
{
break
}
else
{
$array += $line
}
}
This is as far as I've gotten. Nothing I do will get the next section to start reading at a line number and continue through the file from there. Any help would be appreciated.
Upvotes: 1
Views: 214
Reputation: 1782
Try this:
Add-Type -AssemblyName System.Collections
Add-Type -AssemblyName System.Text.RegularExpressions
[System.Collections.Generic.List[string]]$content = @()
$inputFile = 'D:\content.txt'
$outputFile = 'D:\content1.txt'
$addLines = $false
$startLine = 30 # if not needed, set to 0
$lineCounter = 0
foreach($line in [System.IO.File]::ReadLines($inputFile)) {
$lineCounter++
if( $line -like '*Begin of Header*' -or $lineCounter -eq $startLine) {
$addLines = $true
}
elseif( $line -like '*End of Header*') {
break
}
elseif( $addLines ) {
[void]$content.Add( $line )
}
}
[System.IO.File]::WriteAllLines( $outputFile, $content ) | Out-Null
Upvotes: 0