The_DemoCorgin
The_DemoCorgin

Reputation: 744

Want to split a text file into one file per line

I have a text file that is generated daily that has between 20 and 50 lines, each ending with a set delimiter, currently ~ but that can be changed to anything. I want to take this text file and split it into 20 to 50 different files, with one line per file. Ideally I'd like to do this from a windows batch file, or at least a program that I can script to run daily. Appreciate any help you can provide, thanks!

Sample Input File:

GS*SH*CSMZ9*20131209*0908*000000001*X*004010|ST*856*0001|BSN*00*000000001~
GS*SH*CSMZ9*20131209*0912*003400004*X*004010|SG*834*0001|TSN*00*000000004~
GS*SH*CSMZ5*20131209*1001*000040007*X*004010|ST*855*0001|BSN*00*000000007~
GS*SH*CSMZ9*20131209*1019*000000010*X*004010|SG*856*0001|BGN*00*000000010~

Upvotes: 0

Views: 1685

Answers (4)

Magoo
Magoo

Reputation: 79983

@ECHO OFF
SETLOCAL
SET "destdir=c:\destdir"
FOR /f "tokens=1*delims=:" %%a IN ('findstr /n "." q21239387.txt') DO (
 >"%destdir%\filename%%a.txt" ECHO(%%b
)

GOTO :EOF

where q21239387.txt is the name of the file I used as input for testing.

Files filename1.txt..filename99.txt created in the destination directory (99 is # lines in the file)

Note - will not correctly output source lines that begin with : if that is a problem.

Upvotes: 0

foxidrive
foxidrive

Reputation: 41224

This should create files called 00000001.txt and increment the number for each line.

If any line contains ! then it needs an extra modification.

@echo off
setlocal enabledelayedexpansion
set c=0
for /f "delims=" %%a in (file.txt) do (
   set /a c+=1
   set name=0000000!c!
   set name=!name:~-8!.txt
   >!name! echo %%a
)

Upvotes: 0

Endoro
Endoro

Reputation: 37569

for /f "tokens=1*delims=:" %%a in ('findstr /n "^" "file.txt"') do for /f "delims=~" %%c in ("%%~b") do >"text%%a.txt" echo(%%c

Upvotes: 4

pentadecagon
pentadecagon

Reputation: 4847

I propose python here. Much more readable that any shell script.

f=open("filename")
lines = f.read().split('~')
for (n, line)  in enumerate(lines):
    open( "newname{}".format(n), "w" ).write(line)

Upvotes: 1

Related Questions