0

I have a batch file that takes one argument which is a comma separated string and I'm calling it like this:

myBatch.bat ".git,*.tmp,file.c"

Inside the batch file I need to write a code that parses the argument that is passed at the command line and break it like this:

@echo off
set excludes=%~1
set excludes_cmd=""

FOR /f "tokens=1* delims=," %%a IN ("%excludes%") DO (
   set "excludes_cmd=%%excludes_cmd%% --exclude %%~a"
)

So at the end, when I pring the 'excludes_cmd' variable I will get this:

--exclude .git --exclude *.tmp --exclude file.c
3
  • If you are going to use a FOR /F then you need to know how many tokens you will have passed to the script. In your case it is three, so you would be using tokens=1-3 and %%a , %%b and %%c. But you would be better off using a normal FOR command. FOR %%a in (%~1) DO (call set "excludes_cmd=%%excludes_cmd%% --exclude %%~a" Commented Apr 11, 2019 at 15:01
  • @Squashman, a standard for loop will resolve wildcards like * and ?, but I believe this is not what the OP wants... Commented Apr 12, 2019 at 10:56
  • This seems not to be an easy task in pure batch scripting: for resolves wildcards (*, ?), for /F needs a predefined number of items (tokens), sub-string replacement does not care about quotation (I guess there could also occur quoted strings like '.txt' in the argument, which could even contain , on their own, like 'x,y'; right? such commas need to be preserved then)... Commented Apr 12, 2019 at 11:07

2 Answers 2

2

You should be able to do this with basic variable expansion and substitution:

@Echo Off
Set "excludes=%~1"
If Not Defined excludes GoTo :EOF
Set "excludes_cmd=--exclude %excludes:,= --exclude %"

The variable, %excludes_cmd%, should contain your required content.

Sign up to request clarification or add additional context in comments.

Comments

2

Came up with a similar way as Compo, just inserting your examples as defaults.

@echo off
if "%~1"=="" "%~f0" ".git,*.tmp,file.c"
set "excludes=,%~1"
set "excludes_cmd=%excludes:,= --exclude %"
set excludes
excludes=,.git,*.tmp,file.c
excludes_cmd= --exclude .git --exclude *.tmp --exclude file.c

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.