Neil Weicher
Neil Weicher

Reputation: 2502

Batch Script Find String in String with a twist

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'"

Upvotes: 0

Views: 72

Answers (2)

Aacini
Aacini

Reputation: 67216

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%

Upvotes: 0

Joey
Joey

Reputation: 354586

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 ','
}

Upvotes: 3

Related Questions