transpose input file lines to columns w/ separator

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
scavenger
Posts: 18
Joined: 23 May 2015 13:51
Contact:

transpose input file lines to columns w/ separator

#1 Post by scavenger » 20 May 2020 17:21

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

Samir
Posts: 359
Joined: 16 Jul 2013 12:00
Location: HSV
Contact:

Re: transpose input file lines to columns w/ separator

#2 Post by Samir » 22 May 2020 17:37

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. :?

Post Reply