Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

scripting - Split own filename and assign specific parts to variables in a batch script

thanks in advance for any help offered.

I have a batch file from which name i want to use parts and assign them as variables. Using the for /f with delims i was able to do something like it but i have to rename the file to a different scheme than what i need. Se here is what i have:

-Current filename: WHID-PRT-MFP-3, NORTH EAST OFFICE.bat

SET getname=%~n0

for /f "tokens=1 delims=-" %%G IN ("%getname%") DO (SET siteid=%%G)

for /f "tokens=1 delims=," %%E IN ("%getname%") DO (SET name=%%E) 

SET printername=%name%

SET servername=Server-%siteid%-01

OK, so that seems to work ok and im able to get the parts i need from the file name and assign them to variable so that %name%=WHID-PRT-MFP-3 and %siteid%=WHID

Now my dilema is that i need the file name to be: NORTH EAST OFFICE, WHID-PRT-MFP-3.bat So I've been trying to get the entire line behind the comma(WHID-PRT-MFP-3) to a variable and the first item in dashes(WHID) to another variable, same as the example above, but cant figure it out. This will be used with several names so not only as the example shown i could have shorter or longer names for both parts, say: WHID-PRT-1, OFFICE 1

Any ideas are welcome.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

NORTH EAST OFFICE, WHID-PRT-MFP-3.bat:

SET getname=%~n0

rem split at comma
for /f "tokens=2 delims=," %%E IN ("%getname%") DO (

    rem trim space after comma
    for /f "tokens=*" %%S IN ("%%E") DO SET name=%%S

    rem get word before hyphen and strip leading space
    for /f "tokens=1 delims=- " %%S IN ("%%E") DO set siteid=%%S
)

SET printername=%name%
SET servername=Server-%siteid%-01

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...