Page 1 of 1

How to create a variable with arguments starting at 2 positions ?

Posted: 2021-Sep-01, 10:58 am
by PiotrMP006
Hi

How to create a variable with arguments starting at 2 positions ?

set arguments==%*

"D:Test\" "Folder1" "Folder2" "Folder3"


I need to create a variable from the 2nd argument

"Folder1" "Folder2" "Folder3"


Please help me

Re: How to create a variable with arguments starting at 2 positions ?

Posted: 2021-Sep-01, 4:16 pm
by Simon Sheppard

Code: Select all

SHIFT
set arguments=%*

Re: How to create a variable with arguments starting at 2 positions ?

Posted: 2021-Sep-03, 11:21 am
by bluesxman
Simon Sheppard wrote: 2021-Sep-01, 4:16 pm

Code: Select all

SHIFT
set arguments=%*
I don't think that will work Simon, AFAIK %* always contains all of the original args, regardless of "shift" invocations.

You'd probably have to do something like this:

Code: Select all

@echo off

set "args="
call :argloop %*
set args

goto :EOF

:argloop

shift
if "%~1" EQU "" goto :EOF

if defined args (
  set "args=%args% %1"
) else (
  set "args=%1"
)

goto :argloop
Tested as follows:

Code: Select all

C:\Users\bxm>foo.cmd "one" "two" "three ee" "four"
args="two" "three ee" "four"

Re: How to create a variable with arguments starting at 2 positions ?

Posted: 2021-Sep-03, 5:05 pm
by Simon Sheppard
Good point.
I can't help thinking there might be an easier way to approach this, but doing a simple search/replace of %1 within %* will fail if %1 is also contained within any other arguments.

Re: How to create a variable with arguments starting at 2 positions ?

Posted: 2021-Sep-06, 7:16 am
by bluesxman
I agree, it feels like there should be a more elegant solution -- but keeping it robust is tricky without knowing more about the expected input. The only other thing I had in mind was a FOR loop, but it doesn't look any better to me (while probably being marginally worse on performance due to the repeated call invocations). Haven't tested this code:

Code: Select all

@echo off
set "args="
set "count=0"
for %%a in (%*) do call :add_arg "%%~a"
set args
goto :EOF

:add_arg
set /a count+=1
if %count% LEQ 1 goto :EOF
if defined args (
  set "args=%args% %1"
) else (
  set "args=%1"
)
goto :EOF
This solution at least gives you an easy path to skip N args rather than just the first (though the count could easily be back ported to my initial offering).