Home > Net >  Convert multi-record text file to CSV in a Windows Batch File
Convert multi-record text file to CSV in a Windows Batch File

Time:02-01

I have tried several approaches to this and had some success, but now I am trying to stitch it all together and need a little assistance.

The following text file shows three records separated by a blank line. The exact number of records is variable but unlikely to be more than 30.

ITEM 1 SONG
TITLE Blow My Mind (feat. Chris Brown)
ARTISTS Davido
START 00:00:33.6900000
END 00:03:19.2700000

ITEM 2 SONG
TITLE So Good
ARTISTS Alex Blue
START 00:03:19.2700000
END 00:06:01.2330000

ITEM 3 SONG
TITLE Easy To Love (feat. Teddy Swims)
ARTISTS Armin van Buuren and Matoma
START 00:06:07.1430000
END 00:08:37.4520000

Using the following script, I have been able to extract the data and remove the field names:

for /F "tokens=1* delims= " %%A in (text_record.txt) do (

if "%%A" == "ITEM" echo %%B
if "%%A" == "TITLE" echo %%B
if "%%A" == "ARTISTS" echo %%B
if "%%A" == "START" echo %%B
if "%%A" == "END" echo %%B
)

This provides the following result:

1 SONG
Blow My Mind (feat. Chris Brown)
Davido
00:00:33.6900000
00:03:19.2700000
2 SONG
So Good
Alex Blue
00:03:19.2700000
00:06:01.2330000
3 SONG
Easy To Love (feat. Teddy Swims)
Armin van Buuren and Matoma
00:06:07.1430000
00:08:37.4520000

Also, using the following script, I have been able to concatenate first record into a single line CSV:

< text_record.txt ( 
    set /p "line1="
    set /p "line2="
    set /p "line3="
    set /p "line4="
    set /p "line5="
    set /p "line6="
)
set "var=%line1%,%line2%,%line3%,%line4%,%line5%"
echo.
echo("%var%"

This provides the following result:

“ITEM 1 SONG,TITLE Blow My Mind (feat. Chris Brown),ARTISTS Davido,START 00:00:33.6900000,END 00:03:19.2700000"

However, what I want is for each record to be on a separate line, with the field names removed, for example:

1 SONG,Blow My Mind (feat. Chris Brown),Davido,00:00:33.6900000,00:03:19.2700000
2 SONG,So Good,Alex Blue,00:03:19.2700000,00:06:01.2330000
3 SONG,Easy To Love (feat. Teddy Swims),Armin van Buuren and Matoma,00:06:07.1430000,00:08:37.4520000

I think I am close but I need some assistance to pull it together.

CodePudding user response:

Try this:

@echo off
setlocal EnableDelayedExpansion

set "output="
for /F "tokens=1,2* delims=: " %%a in ('findstr /N "^" text_record.txt') do (
   if "%%b" neq "" (
      set "output=!output!,%%c"
   ) else (
      echo !output:~1!
      set "output="
   )
)
if defined output echo !output:~1!
  • Related