batch-filesplitrecord

Batch Script to split record by fixed length


I have an input text file with a single line having thousands of records one after another. I want to split them after length of 10 characters each.

**Input Record** - 
====================== Begin of data =========================
 abcdefghijklmnopqrstuvwxyz1234567890       <= Input file having all records on single line
====================== End of data   =========================

**Expected output** -
====================== Begin of data =========================
 abcdefghij            <= each line of 10 characters
 klmnopqrst
 uvwxyz1234
 567890
====================== End of data   =========================

Please help me to do this using batch script.

Try using Notepad++

It worked well using Notepad++ with below regular expressions -

Find => (?-s).{10}
Replace => ${0}\\r\\n

The record length of 10 above was used only for simplicity, the actual record length is 800 bytes. There are 50 thousand records in each line.


Solution

  • @ECHO OFF
    SETLOCAL
    rem The following settings for the directories and filenames are names
    rem that I use for testing and deliberately includes spaces to make sure
    rem that the process works using such names. These will need to be changed to suit your situation.
    
    SET "sourcedir=u:\your files"
    SET "destdir=u:\your results"
    SET "filename1=%sourcedir%\q78869753.txt"
    SET "outfile=%destdir%\outfile.txt"
    
    (
    FOR /f "usebackqdelims=" %%e IN ("%filename1%") DO SET "line=%%e"&CALL :sub
    )>"%outfile%"
    
    GOTO :EOF
    
    :sub
    IF NOT DEFINED line GOTO :eof
    ECHO %line:~0,10%
    SET "line=%line:~10%"
    GOTO sub
    

    Note that if the filename does not contain separators like spaces, then both usebackq and the quotes around %filename1% can be omitted.

    You would need to change the values assigned to sourcedir and destdir to suit your circumstances. The listing uses a setting that suits my system.

    I deliberately include spaces in names to ensure that the spaces are processed correctly.

    I used a file named q78869753.txt containing your data plus some dummy data for my testing.

    Produces the file defined as %outfile%

    for documentation, see set /? for /? call /? from the prompt or or endless examples on SO.