# Solved: Txt Splitting Help for creation process



## roblooman (May 17, 2011)

hey guys i am fooling around with a simple program and .bats and now i need to split a .txt file
i am working with an encrytion program that needs 3 seperate parts

i am trying to figure out how to split a txt file into 3 equal separate parts 
(any random text file determined by the user that the only common thing is character count and line count)

now i am really concerned about how this is done, my process i am working depends on this

it needs to be split by the number of lines 
(example: 3 lines = 3 text files or 60 lines= 3 text file with 20 each)) 
each with name of original file plus a number or something 
like original.txt > origninal1.txt, original2.txt ect
and after its split each file needs to be still a text file...
or 
if the lines of said text file is less then 3 lines it can be split by character count
30 characters but in 2 lines gets 3 separate file each with 10 characters each

also a way to be able to rejoin these file back together into one text file again would help emensly as well.

i would really love for this to be in a .bat file format or at most a vbs... becuase i want to be able to call it from a .bat file and work along side my other processes... it will be converted into an exe eventualy though at the end
but my programming is pretty limited... but i know .bat fairly well and can call stuff if i need to...such as another script file

i have gnuwin32 tools that has split, and csplit and all the other tools as well if this helps..

but i want to be able to give this program away and have it work on others computers as well who dont have gnuwin32 tools... ((it will all be converted into an exe form))

can anyone help with the .bat or .vbs that can get this done

thanks guys and this forum rocks


----------



## centauricw (Jun 26, 2010)

You can't use a batch (or Windows Command script) to split the text files because this is well beyond the capabilities of a command script, so you'll need to use VBScript. I was intrigued by this that I sat down and wrote a VBScript program to do what you requested. If you follow the comments in the code, you'll see how it works. (I spent a non-trivial amount of time on this, so I did include a copyright but released it under the Open Source BSD license, so you're free to see it as you see fit as long as you remember to credit me.)


```
' splitfile.vbs
' VBScript that will split a text file into three equal parts.

' ----------------------------------------------------------------------------
' PROGRAM LICENSE
'
' Copyright (c) 2011 Charles Rutledge
' All Rights Reserved
'
' Redistribution and use in source and binary forms, with or without
' modification, are permitted provided that the following conditions are met:
'
' * Redistributions of source code must retain the above copyright notice,
'   this list of conditions and the following disclaimer.
'
' * Redistributions in binary form must reproduce the above copyright notice,
'   this list of conditions and the following disclaimer in the documentation
'   and/or other materials provided with the distribution.
'
' * Neither the name of the author nor the names of its contributors may be
'   used to endorse or promote products derived from this software without
'   specific prior written permission.
'
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
' IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
' ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
' LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
' CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
' SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
' INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
' CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
' ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
' POSSIBILITY OF SUCH DAMAGE.
'
' ----------------------------------------------------------------------------

' --- File System Object constants:
Const OverwriteFile = -1
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

' -- Function used to write output files where the source text file is three
'    lines or greater.
Sub WriteOutputFile(ByRef infile, ByRef outfile, ByVal numOfLines)

    readCount = 1
    Do Until infile.AtEndOfStream Or readCount > numOfLines
        outfile.WriteLine(infile.ReadLine)
        readCount = readCount + 1
    Loop

End Sub

' -- Create the system objects needed by the program.
Set fso = CreateObject("Scripting.FileSystemObject")

' -- Check that we have at least one argument, which should be the source text
'    file.  It's possible we could have more than one argument, but all others
'    will be discarded.
If WScript.Arguments.Count = 0 Then
    WScript.Echo "USAGE: splitfile.vbs < textfile >"
    WScript.Quit
End If

 '-- Get the source text file from the command line and verify that it actually
'    exists and uses text file extension (.txt).
SourceTextFile = WScript.Arguments.Item(0)
If Not fso.FileExists(SourceTextFile) Then
    WScript.Echo "ERROR: Text file " & SourceTextFile & " does not exist."
    WScript.Quit
End If
If LCase(fso.GetExtensionName(SourceTextFile)) <> "txt" Then
    WScript.Echo "ERROR: File " & SourceTextFile & " is not a text file."
    WScript.Quit
End If

' -- First we need to get a count of the number of characters and lines in
'    the source text file so we know how to devide it.
Set SourceFile = fso.OpenTextFile(SourceTextFile, ForReading)
LineCount = 0
CharCount = 0
Do While Not SourceFile.AtEndOfStream
    ' -- ReadLine discards the NewLine and CarriageReturn characters, so we
    '    have to accoiunt for them in the character count.
    CharCount = CharCount + Len(SourceFile.ReadLine) + 2
    LineCount = LineCount + 1
Loop
SourceFile.Close

' -- Reopen the source text file and create the three split output files.  The
'    output files use the source text file name and add a number.
Set SourceFile = fso.OpenTextFile(SourceTextFile, ForReading)
Set SplitFile1 = fso.CreateTextFile(Left(SourceTextFile, Len(SourceTextFile) - 4) & "1" & Right(SourceTextFile, 4), vbTrue)
Set SplitFile2 = fso.CreateTextFile(Left(SourceTextFile, Len(SourceTextFile) - 4) & "2" & Right(SourceTextFile, 4), vbTrue)
Set SplitFile3 = fso.CreateTextFile(Left(SourceTextFile, Len(SourceTextFile) - 4) & "3" & Right(SourceTextFile, 4), vbTrue)

' -- If the line count is less then 3 lines, write an equal number of characters
'    to the split output files.  Note that if the character count doesn't divide
'    evenly, the extra characters are added to the last file.
If LineCount < 3 Then
    SplitFile1.Write(SourceFile.Read(CharCount / 3))
    SplitFile2.Write(SourceFile.Read(CharCount / 3))
    SplitFile3.Write(SourceFile.ReadAll)
' -- If the line count is greater then 3 lines, write an equal number of lines
'    to the split output files.  Note that if the line count doesn't divide
'    evenly, the extra lines are added to the last file.
Else
    WriteOutputFile SourceFile, SplitFile1, LineCount / 3
    WriteOutputFile SourceFile, SplitFile2, LineCount / 3
    WriteOutputFile SourceFile, SplitFile3, LineCount / 3 + LineCount Mod 3
End If

' -- Close the files and we're done.
SourceFile.Close
SplitFile1.Close
SplitFile2.Close
SplitFile3.Close
```
Putting the files back together is much simpler. For this, you can use the COPY command. So assuming you have split the file SAMPLE.TXT, you can reassemble it as follows:


```
COPY SAMPLE1.TXT+SAMPLE2.TXT+SAMPLE3.TXT NEWSAMPLE.TXT
```
One word of warning. The COPY command will cause the last character in the NEWSAMPLE.TXT file (which is a carriage-return) as a visible left-arrow.


----------



## roblooman (May 17, 2011)

ok vbs... i can use i can call it....here is the issues i am running into... BTW thanks for the swift reply and code...


ok i need to be able to specifie a file from a batch process of some sort

like


set /p sourcefile= What is the source file? (enter file name ) mytext.txt


start (split scritp) >>%mytext.txt%
echo output file names

-------------
the next part i am confused about to set names of out puts files as inputs
-------------
set file1=mytextpar1.txt
set file2=mytextpar2.txt
set file3=mytextpar3.txt are how ever this is done???


start process file1
start process file2
start process file3
------

this way when my program runs and calls the bat script and the processes run
the main program now has targets to finish processing.
otherwise ill have to put in user input command and i dont want that

it all has to happen in the backround

process looks like:
program starts calls process.bat
bat asks for user input for %sourcefile%
and destination file %destination%
a wait is given for the comptuter to catch up
while the file calls the split script and splits the files and returns
the names as set values %filepar1% %filepar2% ect what ever
then the main program uses thos files and processes them in acordance with the .bat instructions



then

puase<nul
echo Hit any button to continue and recieve your encryted file!
start %destination%

end


whalla
the whole thing is finnished


this is what i need...and i am confused a bit about how your code works tward this fasion
if it dose at all....becuase i left out how it was being used i feel i didn give the whole deal of what was going on....with the process when i looked at the code i saw it was specifing 3 as the line numbers...
but what i need is for it to not car at all about how many are there just to dividde them up into 3 text files
this will be given to other people who all have different length of files to process so thats why it needs to just process what it see and divide accourdingly

i know what i need to do just not HOW it needs to do it...

grrrr... i wish i new vb script.. lol

thanks again for your help please ask any question about
the needs of the process concerning the code interaction
just cant get past this part

Rob


----------



## centauricw (Jun 26, 2010)

As I said before, you can't use a batch script to split the files because it's too complex for a batch file. VBScript will do what you want and you should consider this a good opportunity to learn. I've provided a VBScript that does the basics and you are free to use it as base for what you ultimately need. What you need is a reference.

Check out the Scripting site on MSDN. You will find references and resources for VBScript and other Microsoft scripting languages. And here's the online book _Windows 2000 Scripting Guide_ that will also teach you a good bit. You don't need anything other than Notepad to write VBScript programs, though you can free and commercial editors that provide tons more features than Notepad. I like Textpad (commercial) and Notepad++ (free).

You can run VBScripts from a batch file by using this:


```
cscript //nologo myscript.vbs parameter [parameter ...]
```
Parameters that use spaces must be enclosed by quotes.


----------



## Squashman (Apr 4, 2003)

This in theory can be done with batch but it would take an eternity for a file that had a lot of lines in it to run.

You can use the FIND command to get the number of lines in the file
Use a SET statement to Divide that by the number of output files you need.
Use a for loop to parse the input file.
Inside the for loop setup 2 counters. (1 for the number of lines you processed and another to keep track of what output file you are on)
Use an IF statement to check to see if the number of lines you have processed equals your split count. If it does equal your split count then increment your output file number up one. And reset your lines processed count back to zero.
You will need to use an IF statement to check to see if you are on your last file. If so then dump the remaining records to the last file. So basically if your input was 61 lines and you are outputting 3 files then the last one will have 21 lines.


----------



## roblooman (May 17, 2011)

i wouldnt have any idea how to implament that... do you got code to show for this... it seems like that will work...

Rob


----------



## roblooman (May 17, 2011)

ok.....got that figured out..... now i need to get them back together again

and the 

copy mytext.txt+mytext.txt+mytext.txt lasttext.txt

isnt work the right way.
maybe my batch is to big or calling to much stuff..

als tried the 

type nul>final.txt
type mytext.txt >>final.txt
type mytext2.txt>>final.txt
type mytext3.txt>>final.txt isnt work right either

i keep getting echo off errors inside the processed text files
and whats more worse is that it adds the lines to the end of the last line and not to the new line i need it in...

this is my text here. this is my text here (wrong)

this is my text here.
this is my text here. (right)

is there a work around for this using vbs?


----------



## Squashman (Apr 4, 2003)

The copy command would be the correct way to get them all back together. Your syntax looks correct other than using the same filename 3 times in a row.

I always use the /B switch with the copy command. I know it says binary but this keeps the copy from adding an END OF FILE character after it appends all the data together.


----------



## roblooman (May 17, 2011)

i think i got it now... the guy i am working with on this progect for got to tell me that the encoding characters he uses use the same characters as batch script characters and text files end of line calls...so i was worried about nothing...96 hours of my life i want back

with the help of you guys and the split code i was able to concure the stupid batch monster....

i basically created a program out of pure batch and used calls to help vbs and batches to do the other jobs....

it all good now... thanks guys

Rob


----------



## Squashman (Apr 4, 2003)

Would be great to see your final code and if your thread is solved then use the Thread Tools link at the top of your first post to mark your Thread Solved.


----------

