stackbacker
stackbacker

Reputation: 329

Win Batch - split & concatenate

I have a comma delimited string that is formatted like this:

host1.mydomain.net,host2.mydomain.net,host3.mydomain.net

I'm trying to use batch (not allow to install additional software or use powershell) to prepend "http://" and append ":8080" to each hostname then string them all together.

http://host1.mydomain.net:8080,http://host2.mydomain.net:8080,http://host3.mydomain.net:8080

Below is just one method I've tried, splitting the string then creating a new one but while I was able to extract each hostname, I can't seem to concatenate them. Also thought about prepending the "http..." to the beginning of the string, ":8080" to the end, and replacing each comma with ":8080,http://" but I can't get the prepending to work. If this were Linux & sed it'd be pretty straightforward, but batch sting manipulation has always been tough for me.

@echo off
set themes=Host1,Host2,Host3
set NEWSTR1=
echo list = "%themes%"
for %%a in ("%themes:,=" "%") do (
   echo hostname is %%~a
   if NOT DEFINED NEWSTR1 (      
      set NEWSTR1=remote://%%~a:4447
      echo.%NEWSTR1%
   ) ELSE (
      set NEWSTR1=%NEWSTR1%,remote://"%%a":4447
      echo In the else %NEWSTR1% )
)

echo %NEWSTR1%

Upvotes: 0

Views: 362

Answers (1)

aschipfl
aschipfl

Reputation: 34909

You could simply use substring replacement here, like this:

set "themes=Host1,Host2,Host3"
set "NEWSTR1=http://%themes:,=:8080,http://%:8080"

So every , becomes replaced by :8080,http://; after prepending http:// and appending :8080 to the whole string, you get the desired result.

Upvotes: 6

Related Questions