header image

Splitting a file

Posted by: | February 25, 2019 Comments Off on Splitting a file |

Saw a question about splitting a file that had repeating data blocks.

Each block starts with HOST so the code to split becomes:

$fnum = 1

Get-Content -Path C:\test\Data.txt |
ForEach-Object -Process {
if ($_ -like ‘HOST*’) {
$file = “C:\test\outdata{0:00}.txt” -f $fnum
$fnum ++
}

Add-Content -Path $file -Value $_
}

 

Initialise a counter variable $fnum

 

Get the file content and for each line test if it starts with HOST. If so create a new file name by using the format operator to substitute $fnum into the file path. {0:00} means put $fnum into the filed and ensure that its 2 digits so outdata01.txt instead of outdata1.txt. Increment $fnum

 

Write the line to the file.

under: PowerShell

Comments are closed.

Categories