Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read file into array and write chunks out

Tags:

batch-file

cmd

i have a file with the following content:

1005
1010
1011
1012
1013
1014
1009
1015
1006
77
1016
1017
1018
1019
1020
1021
1022
1023
1008

i want to read those lines into an array, sort them and write out chunks with 5 elements into a new file

the output file should looks like this (five elements each line.)

xyz 77,1005,1006,1008,1009
xyz 1010,1011,1012,1013,1014
...

my current batch script looks like this:

@echo off &setlocal disabledelayedexpansion

Sort Knot_unsort.dat>Knot_sort.dat

set /A i=0

for /F "delims=" %%a in (Knot_sort.dat) do (
    set /A i+=1
    call set array[%%i%%]=%%a
)
call set n=%%i%%

for /L %%i in (1,1,%n%) do (
    set /a b = %%i %% 5

    if %b% == 0 (
        :: does not work
    )

    call echo %%b%%
)

sorting the content and reading the lines into a array works. but after that i dont know how to concat five elements into a new variable and write them back into a new file. i tried to use modulo but the if statement is not working.

like image 790
JuKe Avatar asked Apr 09 '26 20:04

JuKe


1 Answers

Another simpler approach, that don't store the lines in variables...

EDIT: Small bug fixed

@echo off
setlocal EnableDelayedExpansion

set "i=0"
<nul (for /F %%a in ('sort Knot_unsort.dat') do (
   set /A "i=(i+1)%%5"
   if !i! equ 1 (set /P "=xyz %%a") else set /P "=,%%a"
   if !i! equ 0 echo/
))
if %i% neq 0 echo/

Output:

xyz 1005,1006,1007,1008,1009
xyz 1010,1011,1012,1013,1014
xyz 1015,1016,1017,1018,1019
xyz 1020,1021,1022,1023

EDIT: New method to manage numbers with variable number of digits, up to 8

@echo off
setlocal EnableDelayedExpansion

set "i=0"
<NUL (
   for /F "tokens=2 delims=/ " %%a in (
      '(for /F %%i in (Knot_unsort.dat^) do @(set /A 100000000+%%i ^& echo /%%i^)^) ^| sort'
                                      ) do (
      set /A "i=(i+1)%%5"
      if !i! equ 1 (set /P "=xyz %%a") else set /P "=,%%a"
      if !i! equ 0 echo/
   )
)
if %i% neq 0 echo/
like image 123
Aacini Avatar answered Apr 13 '26 08:04

Aacini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!