开发者

batch: How can i call second parameter with spaces?

开发者 https://www.devze.com 2023-02-08 08:30 出处:网络
I\'m calling a batch file with two params, like this: C:\\myBatch.bat username hello this is text Now i want to access username (no problem, %1). But i want now to get all other words in one second

I'm calling a batch file with two params, like this:

C:\myBatch.bat username hello this is text

Now i want to access username (no problem, %1). But i want now to get all other words in one second parameter. If I call %2, there is only "hello". And it is not possible that I call the batch开发者_JS百科 file with double quotes around the text...

Any Idea? (something like a while %i != "" then do it in one var..)?


Just using double quotes is the proper way to pack a space separated string into a single parameter, but as a alternative, you can use FOR to parse the "all parameters variable" (%*).

@echo off
FOR /F "tokens=1,*" %%A in ("%*") do (
    echo.Username=%%A
    echo.Message=%%B
)

When called as test.cmd nickname foo bar baz it prints:

Username=nickname 
Message=foo bar baz

I guess that is what you want?


Put the second parameter in double quotes when calling the batch script.

In the batch script use %~2 to reference the second parameter without the quotes.

If you want to use double quotes inside the quoted parameter, duplicate the quote character. With the dequoting in the batch script duplicated quotes are removed too, AFAIK.


Here's a simple script illustrating the idea:

@ECHO OFF
ECHO %1 %2
ECHO %~1 %~2

Now call it like this:

mybatch.bat username "hello this is text"

and see the result:

username "hello this is text"

username hello this is text

That is, when you use %i to reference a parameter, the quotes, if there are any, are retained, but %~i effectively removes them for you.

And, as you can see from %~1 use, if there are no quotes, the output is just the same as with %1, so you don't need to always include quotes simply to justify the tilde use.


Based on this doc http://ss64.com/nt/syntax-esc.html double quotes should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消