Script that split files into parts accidentally creates empty lines at the end PowerShell

40 views Asked by At

I make this script that split all the files in the current path and subfolders into files of 100 thousand characters each. It respects the lines, so it does not divide them in half. The last line that exceeds 100 thousand characters is removed and added to the next part. The problem is that each split part has 2 empty lines at the end, always, and I cannot remove them. If the file had other blank lines I would like it to keep them, even if they are at the end of a part.

# Defining the function to divide the text into parts of up to 100,000 characters.
function DivideText($text) {
    $maxCharacters = 100000
    $parts = @()

    $currentPart = ""
    $lines = $text -split "`n"
    foreach ($line in $lines) {
        # Check if adding the current line would exceed the maximum character limit.
        if (($currentPart.Length + $line.Length + 2) -le $maxCharacters) {  # Add 2 to account for new line character
            $currentPart += $line + "`n"
        } elseif ($currentPart.Length -eq 0) {
            # If the current part is empty and cannot contain the current line, add the line directly as a part
            $parts += $line
        } else {
            # Add the current part only if it is not empty.
            if ($currentPart.Trim("`n") -ne "") {
                $parts += $currentPart.Trim("`n")
            }
            # Start a new part with the current line
            $currentPart = $line + "`n"
        }
    }

    # Add the last part if it is not empty.
    if ($currentPart.Trim("`n") -ne "") {
        $parts += $currentPart.Trim("`n")
    }

    return $parts
}

# Get the list of all files in the current folder and subfolders.
$files = Get-ChildItem -Path . -File -Recurse -Filter *.txt

foreach ($file in $files) {
    # Read the contents of the file
    $content = Get-Content $file.FullName -Raw

    # Divides the text of the file into parts
    $parts = DivideText $content

    # Rename the original file
    $originalName = $file.FullName
    $originalExtension = $file.Extension
    $originalNameWithoutExtension = $file.FullName -replace $originalExtension, ""
    $originalBaseName = $file.BaseName
    $i = 1

    # Write the parts in separate files
    foreach ($part in $parts) {
        $partNumber = "{0:D2}" -f $i
        $partFileName = "{0}Parte{1}.txt" -f $originalNameWithoutExtension, $partNumber
        Set-Content -Path $partFileName -Value $part
        $i++
    }

    # Delete the original file
    Remove-Item $originalName -ErrorAction SilentlyContinue
}

Write-Host "File division completed."
0

There are 0 answers