Split txt file after a given word

October 12, 2009 at 12:21:48
Specs: Windows Vista & UBUNTU

Hello guys, i want to do a batch file to split a text file into multiple txt files every time there is a given word inside the txt.

for example:

(content of text.txt)
bla bla bla bla
CAR No. 1
bla bla bla bla
bla bla bla bla
CAR No. 2
bla bla bla bla
bla bla bla bla
bla bla bla bla
CAR No. 3

and i want to split it into 3 txt files, the first of them containing CAR No.1 and bla bla bla...
the second containing CAR No.2 and bla bla

and so on.

thanks in advance.


See More: Split txt file after a given word

Report •


#1
October 12, 2009 at 14:00:54
@echo off & setLocal EnableDELAYedExpansion

if exist file?.txt del file?.txt

for /f "tokens=* delims= " %%a in (text.txt) do (
set str=%%a
echo !str! | find "CAR No" > nul
if not errorlevel 1 (
set dest=!str!
if defined dest set dest=!dest:~-1!
)
if defined dest echo !str!>> file!dest!.txt
)


=====================================
Helping others achieve escape felicity

M2


Report •

#2
November 5, 2009 at 06:32:29
XmlMax will do this using an xpath expression. It will do it in a single pass using the unqiue file names option, but it does not run in batch mode. It is a GUI program. Get the free trial from xponentsoftware

Report •

#3
November 6, 2009 at 04:36:28
It obviously wasn't urgent.


=====================================
Helping others achieve escape felicity

M2


Report •

Related Solutions

#4
November 9, 2009 at 08:29:40
# Script SplitFile.txt
var str file, str
var str content ; cat $file > $content
while ( { sen -c -r "^"+str+"&\n^" $content } > 0 )
do
    echo "\n\n\n\nNEXT SPLIT FOLLOWS.\n"
    stex -c -r "^"+str+"&\n^]" $content
done
echo "\n\n\n\nLAST SPLIT FOLLOWS.\n"
echo $content

Script is in biterscripting ( http://www.biterscripting.com ) . Save the script in file C:/Scripts/SplitFile.txt, call it using the command

script "C:/Scripts/SplitFile.txt" file(C:/text.txt") str("CAR No.")

Will show you splits of file C:/text.txt split at the string "Car No.". To create split files, just redirect the output of the stex command with > . Increment the file name after each split.



Report •


Ask Question