Page 1 of 1

transpose input file lines to columns w/ separator

Posted: 20 May 2020 17:21
by scavenger
I needed to transpose a file's content into a variable number of columns, line by line:
  • input
a aa
b b b
ccc
ddd
  • output (2 columns, separator=" ")
a aa b b b
ccc ddd

Couldn't find anything close to this in the forum, and using xargs.exe was out of the question as lines could contain spaces

So instead of asking and being trolled for simply asking like I was the other day, I wrote the code and am sharing it below.
It works with text lines containing spaces and special characters wuch as " \ , = % ^ %
Indeed, it works better with an input file containing a number of lines divisible by the number of columns...

Code: Select all

:: :transpose each input file line to output file with numColumns
:transpose input output numColumns [separator]
set input=%1
set output=%2
set numColumns=%3
set "separator=%^4"

IF %numColumns% EQU 1 copy /y %input% %output% >NUL 2>&1 & exit /b 0
setlocal enabledelayedexpansion

set count=0
for /f "tokens=*" %%L in (%input%) DO (
  set /A count+=1
  SET /a MODULUS=!count!%%%numColumns%
  IF !MODULUS! EQU 0 (echo %%L>>%output% & set count=0) ELSE <nul set /p =%%L%separator%>>%output%
)

setlocal disabledelayedexpansion
goto :EOF

Re: transpose input file lines to columns w/ separator

Posted: 22 May 2020 17:37
by Samir
Thank you for sharing. I remember a long time ago there was a bath for something similar if not the exact same thing, but who knows how to find it. :?