Skip to content

Instantly share code, notes, and snippets.

@Stuart-Moore
Last active August 5, 2016 10:30
Show Gist options
  • Save Stuart-Moore/75690fa0ef83c04c1806614f2f0af014 to your computer and use it in GitHub Desktop.
Save Stuart-Moore/75690fa0ef83c04c1806614f2f0af014 to your computer and use it in GitHub Desktop.
Split file on blank lines in powershell, quick and dirty
$testtext = @"
test1
test 2
The quick brown fox jumps over the lazy fox
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
test4
test4a
test4b
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
"@
$testtext | Out-File .\testfile.txt
$output = @()
$plineblank = $false
$tline = ''
$tmp = Get-Content .\testfile.txt
Foreach ($line in $tmp){
if ($line -eq '' -and $pline -ne '' ){
$output += $tline
$tline = $null
} else {
$tline = $tline+"`n"+$line
}
$pline = $line
}
$output += $tline
@Stuart-Moore
Copy link
Author

$output is an array, so each element contains the set of lines between the blank ones.

ie;
$output[4] returns all these:
test4
test4a
test4b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment