1.

Solve : Cut a text file after N specific strings found?

Answer»

Hi,
I have a big text file and I would like to cut it into 2, 3, 4, ... (x) files, depending how big it is.

I open the SOURCE file and I begin COPYING to the destination file (which has the same name with a digit at its end). When I find the search string I begin counting.
At the Nth string found I should create a new file and begin copying to it.

Below is the code I have but I can't detect the searched string.

Thanks for your help.

:: NAME : SplitInNFiles.BAT
:: USAGE: SplitInNFiles [device:][pathname]filename
@echo off & setlocal EnableDelayedExpansion

:: Check for the paramètre
set param=%*
if not defined param (
echo.
echo. Usage: split [device:][pathname]filename
goto :EOF
)

:: check if the file exist
set param=%param:"=%
if not exist "%param%" (
echo.
echo. File "%param%" not found
goto :EOF
)

:: EXTRACT the file name and its extension
for %%j in ("%param%") do (
set name=%%~dpnj
set ext=%%~xj
)

:: COUNT in how MANY files it should be cut
set nbTransac=700
set strSearched=String to look for

for /F %%j in ('type "%param%" ^| find /C /I "%strSearched%"') do set lgTrouve=%%j
set /A nbFichier = (%lgTrouve% / %nbTransac%)+1
echo %lgTrouve%
echo %nbFichier%

:: Verify if cut is necessary
set i=0
if %nbFichier% EQU 1 (
Goto :EOF
) ELSE (
:: Start spliting
set i=1
set N=1
type nul > "%name%_!i!%ext%"

for /F "tokens=1* delims=]" %%j in ('type "%param%" ^| find /V /N ""') do (
echo.%%k>> "%name%_!i!%ext%"
Set subStr=%%k:~0,12%%

rem GIVES ME AN ERROR! if %SubStr% EQU %strSearched% set /A N=%N%+1

:: Reset counts
if !N! gtr %nbTransac% (
set /A i=%i%+1
type nul > "%name%_!i!%ext%"
Set N=1
)
)

REM "delete original file"
)

:EOF
no need to reinvent the wheel....you can download GNU split utility (from coreutils) (see my sig for link). there are also plenty of tools capable of doing such task. just have to search for it.



Discussion

No Comment Found