Search code examples
cmdforeachpivottranspose

CMD - Pivot / Transpose lines of file [e.g. convert 1500 lines (x1 col) --> 500 lines (x3 col)]


how please can I 'pivot' or transpose a file (i.e. turn a single-column list, into a table of data)...

Currently...

VideoA.name
VideoA.size
VideoA.bitrate
VideoB.name
VideoB.size
VideoB.bitrate
...

Desired...

VideoA.name, VideoA.size, VideoA.bitrate
VideoB.name, VideoB.size, VideoB.bitrate
Name Size Bitrate
VideoA.name VideoA.size VideoA.bitrate
VideoB.name VideoB.size VideoB.bitrate

Extra Info / Context

I'm aware people often ask 'why are you doing this?' so (if interested), here is the wider context / problem I am trying to solve...

  • I have a list of files in Files.txt
  • I have a jscript batch file getProps.bat that extract file properties and prints them, 1 per line
  • I have written a batch file to loop through Files.txt, get the properties of each and write the output to Details.csv
  • However if I have 500 files x 3 properties, this currently gives me 1500 lines, and I want 500 lines x 3 columns
GetProps_AllFiles.bat
---------------------

@ECHO OFF
SETLOCAL
FOR /F "tokens=*" %%A in (Files.txt) do (
    getprops %%A 0,1,320 /noheaders >> Details.csv
)

Thanks in advance!


Solution

  • Use the "standard way" (for /f) to read a file line by line, extended by a counter. Add the line to a string (line), followed by a comma (or whatever you want to use as separator), and increase the counter. Except it's the third line. Then print the string plus the current line, reset the counter and string, and repeat.

    @echo off
    setlocal enabledelayedexpansion
    set "line="
    set count=0
    (for /f "delims=" %%a in (test.txt) do (
      set /a count+=1
      if !count! equ 3 (
        echo !line!%%a
        set "line=" 
        set count=0
      ) else (
        set line=!line!%%a,
      )
    ))>test.csv