Rommy
Rommy

Reputation: 23

Batch: split values into separate line with specific pipe delimiter

I'm trying to create a report that will split into next row for each line. My data:

I,have,a,report,to,split,|,into,next,row
my,second,line,should,also,|,split,like,before

then it should be like this:

I,have,a,report,to,split
into,next,row
my,second,line,should,also
split,like,before

I have tried the script:

@echo off
setLocal
for /f "tokens=1 delims=.|" %%a in (input.csv) do echo %%a
for /f "tokens=2 delims=.|" %%a in (input.csv) do echo %%a

but the result is:

I,have,a,report,to,split
my,second,line,should,also
into,next,row
split,like,before

Anyone can help me with this? thanks in advance…

Upvotes: 2

Views: 654

Answers (1)

Aacini
Aacini

Reputation: 67216

Your result example is wrong. This is the output from your code:

I,have,a,report,to,split,
my,second,line,should,also,
,into,next,row
,split,like,before

Note the comma at end of line 1 and 2, and at beginning of line 3 and 4

This method works:

@echo off
setlocal EnableDelayedExpansion

rem Define a variable with CR+LF ASCII chars:
for /F %%a in ('copy /Z "%~F0" NUL') do set CRLF=%%a^
%empty line 1/2%
%empty line 2/2%

rem Change each ",|," string by CR+LF characters
for /F "delims=" %%a in (input.csv) do (
   set "line=%%a"
   for %%N in ("!CRLF!") do echo !line:,^|,=%%~N!
)

Of course, you may also do it in the "traditional" :/ way:

@echo off
setlocal EnableDelayedExpansion

for /F "tokens=1,2 delims=|" %%a in (input.csv) do (
   set "left=%%a"
   set "right=%%b"
   echo !left:~0,-1!
   echo !right:~1!
)

Upvotes: 1

Related Questions