Search code examples
batch-filecmdwindows-scriptingbatchingfilesplitting

While splitting txt file through batch script Exclamations are ommitting


Iam new to batch script and here I tried to split my text file into chunks for each 1 million rows. Chunk files are generated as I expected, but inside the output file content Iam missing the Exclamations ( ! ) and even it skipping the immediate column after Exclamation. Please help me to get data as it is in original file into chunks!

@ECHO OFF
setLocal DisableDelayedExpansion

set limit=1000000
set feed_name=test.txt
set file=%Tgt_Dir%\%feed_name%
set lineCounter=1
set filenameCounter=1
set name=
set extension=


for %%a in (%file%) do (
    set "name=%%~na"
    set "extension=%%~xa"
)

setlocal enabledelayedexpansion
for /f "tokens=*" %%a in (%file%) do (
    set splitFile=!name!%date:~12,2%%date:~4,2%%date:~7,2%!filenameCounter!!extension!
    if !lineCounter! gtr !limit! (
        set /a filenameCounter=!filenameCounter! + 1
        set lineCounter=1
        echo Created !splitFile!.
    )
    echo %%a>> %Tgt_Dir%\!splitFile!

    set /a lineCounter=!lineCounter! + 1
)
endlocal

It is a Tab delimiter file.

ScreenShot enter image description here


Solution

  • You need to toggle delayed expansion.

    setlocal DisableDelayedExpansion 
    for /f "tokens=*" %%a in (%file%) do (
        Set "line=%%a"
        setlocal  EnableDelayedExpansion 
    
            set splitFile=!name!%date:~12,2%%date:~4,2%%date:~7,2%!filenameCounter!!extension!
    
            echo(!line!>> %Tgt_Dir%\!splitFile!
    
        if !lineCounter! gtr !limit! (
            ENDLOCAL
            set /a filenameCounter+=1
            set lineCounter=1
            echo Created file
        ) ELSE ENDLOCAL
        set /a lineCounter=lineCounter + 1
    )