T
T
Timafey Sadovykh2021-01-28 20:57:28
cmd/bat
Timafey Sadovykh, 2021-01-28 20:57:28

Crop txt file using cmd?

I would like to truncate a text file that has about 240000 lines. I want to trim it every 1000 lines and save it as a new text file and name it in order.

@echo off
setlocal enableDelayedExpansion

set "src=result3.txt"

:: Redirect input to the source file
call :main "%src%" <"%src%"
exit /b


:main

::Get number of lines in file
for /f %%N in ('type "%src%"^|find /c /v ""') do set cnt=%%N

::Get first line to use as header for each file
set "header="
set /p "header="

set /a fileNum=1, lineNum=0
 :loop
  :: Exit if done
  if !lineNum! geq !cnt! exit /b

  :: establish zero padded numeric suffix
  set "suffix=000!fileNum!"
  set "suffix=!suffix:~-4!"

  >"%~n1_!suffix!%~x1" (
    echo(!header1!
    for /l %%N in (1 1 1000) do if !lineNum! lss !cnt! (
      set /a lineNum+=1
      set "ln="
      set /p "ln="
      echo(!ln!
    )
  )
  set /a fileNum+=1
  goto :loop

But strange, and often empty files come out,
for example:
4

3

3

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question