Cloud
Cloud

Reputation: 1034

Change each line of text to each column of csv file

I have a text file. For example

 This is computer
 That one is monitor
 Some products are printer

I want to save each line of data into each column of csv file as a one row.

expected result

So, I try to create a batch file like this.

@ECHO OFF
setlocal ENABLEDELAYEDEXPANSION
set file=a.txt
set content=
echo %file%
for /F  %%i in (a.txt) Do (
        set content=!content!,%%i
    )
echo %content%>>result.csv
pause

But I get only the first word from every line of text.

result

When I try to add tokens=* to for loop,

for /F "tokens=*"  %%i in (a.txt) Do....

I got the error: The system cannot find the file specified.

I'm not understand whats wrong with my code and I'm not familiar with batch script.

Upvotes: 0

Views: 110

Answers (2)

Compo
Compo

Reputation: 38579

You need to ensure that your protecting spaces in your line content and file names:

@Echo Off
SetLocal EnableDelayedExpansion
Set "fIn=a.txt"
Set "fOut=result.csv"
Set "str="
For /F "UseBackQ Delims=" %%A In ("%fIn%") Do Set "str=!str!,%%A"
If Defined str >>"%fOut%" Echo(%str:~1%

Edit

A slight alternative to cater for some potential problematic characters which may exist in the not provided content of the file:

@Echo Off
SetLocal DisableDelayedExpansion
Set "fIn=a.txt"
Set "fOut=result.csv"
Set "str="
SetLocal EnableDelayedExpansion
For /F "UseBackQ Delims=" %%A In ("%fIn%") Do Set "str=!str!,%%A"
EndLocal & Set/P "=%str:~1%"<Nul>>"%fOut%"

Upvotes: 1

MichaelS
MichaelS

Reputation: 6032

There were several bugs in your code. I've fixed them so now a proper csv string is being generated. However, newer Excel versions actually use ; instead of , to separate cells. This is your code:

@ECHO OFF
setlocal ENABLEDELAYEDEXPANSION
set file=a.txt
for /F %%i in (%file%) Do (
        set content=!content!;%%i
    )
set content=!content:~1!
echo %content%>>result.csv
pause

Upvotes: 0

Related Questions