0

I'd like to have a batch file which will convert my csv that is in format

value1,value2,value3

into

"value1","value2","value3"

I tried to do the same in Excel file directly (according to this answer https://stackoverflow.com/a/38728364) but when I'm saving the file I see in notepad that it is

"""value1""","""value2""","""value3"""

Only with vba script it worked but it is not convenient to use. So now I'm looking for some script that will handle this in faster way than opening an excel, selecting range and uploading VBA script to convert values. I found powershell script, but it is not valid in my case. I googled and found only how to remove the quotes, not how to add them :D

Do you have any other ideas how to achieve this in Excel directly or in batch file?

jm.
  • 3
  • 2
  • You can try an addaption of this script: https://support.microsoft.com/nl-nl/help/291296/procedure-to-export-a-text-file-with-both-comma-and-quote-delimiters-i – Alex de Jong Mar 02 '19 at 21:30
  • Doesn't Excel put quotes around CSV fields that contain data as text? (I can't test at the moment...) Anyway, what batch file have you tried, where are you stuck? Please provide a [mcve] of your coding attemts! Also read the [tour] and learn [ask]! – aschipfl Mar 02 '19 at 21:47
  • [parsecsv.bat](https://www.dostips.com/forum/viewtopic.php?t=5702) – Squashman Mar 02 '19 at 23:25

1 Answers1

0

You could do the following (see the explanatory rem remarks):

@echo off
rem // Read CSV file that is provided as command line argument:
for /F "usebackq delims=" %%L in ("%~1") do (
    rem // Store currently read line:
    set "LINE=%%L"
    rem /* Toggle delayed expansion to be able to write and read a variable in the same block of code
    rem    (without it reading a variable would return the value present before the whole block executes): */
    setlocal EnableDelayedExpansion
    rem /* Return the current line but enclose it within `""`
    rem    and replace every `,` by `","`;
    rem    this results in every comma -separated field to appear in between quotes: */
    echo("!LINE:,=","!"
    endlocal
)

This relies on the assumption that no field value contains commas on its own.

aschipfl
  • 33,626
  • 12
  • 54
  • 99