0

I am trying to do this in a batch script, which should be simple, but after spending a couple of hours on it I am no closer to a solution.

If the CMD parameter contains a series of letters, I want to surround each letter with single quotes and separate by commas. For example, if the user enter this:

MYTEST.CMD ABCDEF

I want to create a string that looks like this:

'A','B','C','D','E','F'

The same as if they had entered this in the CMD line:

MYTEST.CMD "'A','B','C','D','E','F'"

2 Answers 2

3

Fairly easy, actually:

@echo off
set "LETTERS=%~1"
set OUTPUT=

if not defined LETTERS goto usage

:loop
  if defined OUTPUT set "OUTPUT=%OUTPUT%,"
  set "OUTPUT=%OUTPUT%'%LETTERS:~0,1%'"
  set "LETTERS=%LETTERS:~1%"
  if defined LETTERS goto loop

echo.%OUTPUT%
goto :eof

:usage
echo Please pass a few letters as argument, e.g.
echo.  %~0 ABC
goto :eof

Let's dissect it a little:

  1. We first store the argument in the variable LETTERS.
  2. Then we initialise our output string to an empty string.
  3. Then follows a loop that appends the first letter from LETTERS to OUTPUT in the proper format (with a comma before if OUTPUT is not empty) and removes that letter from LETTERS.
  4. When LETTERS is empty, we exit the loop and print the result.

And just for the fun of it, the same as a PowerShell function:

function Get-LetterList([string]$Letters) {
  ([char[]]$Letters | ForEach-Object { "'$_'" }) -join ','
}
Sign up to request clarification or add additional context in comments.

2 Comments

Should use set "letter=%~1" in case argument is already quoted.
Good point, indeed. And if that is your only complaint then I did at least some things right ;-)
0

The Batch file below use an interesting trick I borrowed from this post that convert the Ascii (1-byte) characters into Unicode 2-bytes characters via cmd /U (inserting a zero-byte between characters), and then split the zero-bytes in individual lines via find command:

@echo off
setlocal EnableDelayedExpansion

set "output="
for /F "delims=" %%a in ('cmd /D /U /C echo %~1^| find /V ""') do (
   set "output=!output!,'%%a'"
)
set output="%output:~1%"
echo %output%

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.