Friday, January 24, 2014

Powershell: Divide text file lines between two files (req.)

This week I received a question about a Powershell script I wrote to split large text files to multiple files.
So I decided to answer that with blog post in which a similar script divides lines of a text files between two text files. Nothing fancy, it's rather basic script :)

This script just checks whether the line count increment is either odd or even. Based on that outcome, the results goes to output file 1 or 2.

#Script initialization
$linecount = 0
$sourcefilename = Read-Host "What is the full path and name of the log file from which you want to divide the lines? (e.g. D:\mylogfiles\mylog.txt) "
$destinationfolderpath = Split-Path $sourcefilename -parent

$srcfile = gci $sourcefilename
$filebasename = $srcfile.BaseName
$fileext = $srcfile.Extension

#Functions
Function check-even ($num) {[bool]!($num%2)}

#Main
Get-Content $sourcefilename | Measure-Object | ForEach-Object { $sourcelinecount = $_.Count }

Write-Host "Your current file size is $sourcelinecount lines long"
Write-Host File is $sourcefilename - destination is $destinationfolderpath

$content = get-content $sourcefilename | % {
 $linecount ++
 If(Check-Even($linecount)) {
    Write-Host "Writing part: $destinationfolderpath\$filebasename`_part2$fileext"
    Add-Content $destinationfolderpath\$filebasename`_part2$fileext "$_"
 } else {
    Write-Host "Writing part: $destinationfolderpath\$filebasename`_part1$fileext"
    Add-Content $destinationfolderpath\$filebasename`_part1$fileext "$_"
  }
}

0 reacties:

Post a Comment