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

Microsoft Windows
Post Reply
PiotrMP006
Posts: 19
Joined: 2021-Sep-01, 10:57 am

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

Post 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
bluesxman
Posts: 10
Joined: 2021-Jul-26, 3:41 pm

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

Post 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"
User avatar
Simon Sheppard
Posts: 190
Joined: 2021-Jul-10, 7:46 pm
Contact:

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

Post 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.
bluesxman
Posts: 10
Joined: 2021-Jul-26, 3:41 pm

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

Post 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).
Post Reply