2013-04-20 10:01, Gabor Grothendieck:
> I have a string that I wish to prepend to my path, say:
>
> set x=C:\A;C:\A;C:\B;C:\A;C:\B;C:\B;C:\A
>
> Typically x has about 6 components but only 2 unique ones.
> I do not know ahead of time what the components are. I would
> like to remove all but the first occurrence of any component.
> We can assume that duplicate components appear in the exact
> same form as the non-duplicates, (e.g. we would never have
> both C:\X\Y and C:/X/Y). In the above example variable x's
> value is the input and the result would be:
>
> C:\A;C:\B
Here's a short subroutine which does that; it looks larger because of
all the comments. It is contained in a demonstration script. In it is
set to prefix as you specified but it can be changed to append by moving
REM to the other line where it reads "If DEFINED #".
It can be used to set the path variable so that redundancies do not
occur, or it can be called after all the additions to remove
redundancies.
:: BEGIN SCRIPT :::::::::::::::::::::::::::::::::::::::::::::::::::::
:: From the desk of Frank P. Westlake, 2013-04-21
:: Written on Windows 8.
@Echo OFF
SetLocal EnableExtensions EnableDelayedExpansion
:: EXAMPLE: Trim, don't add.
Set "X=C:\A;C:\B;C:\A;C:\B;C:\A;C:\B"
CALL :trimPath:x
Echo X=!X!
:: EXAMPLE: Trim and add bunchos more.
Set "X=C:\A;C:\B;C:\A;C:\B;C:\A;C:\B"
CALL :trimPath:x "C:\A&B" "C:\C&D" C:\E\F\G
Echo X=!X!
:: EXAMPLE: Trim and add bunchos more with forward slants.
Set "X=C:/A;C:/B;C:/A;C:/B;C:/A;C:/B"
CALL :trimPath:x "C:/A&B" "C:/C&D" C:/E/F/G
Echo X=!X!
Goto :EOF
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:trimPath:<variable to trim> [segment to add]
:: Eliminates redundant path segments from the variable and
:: optionally add new segmants.
:: Example: CALL :trimPath:PATH
:: Example: CALL :trimPath:PATH "C:\A&B"
::
:: Note that only a colon separates the subroutine name and
:: the variable name to edit.
SetLocal EnableExtensions EnableDelayedExpansion
Set "$="
For /F "tokens=2 delims=:" %%a in ("%0") Do Set "old=!%%a!"
For %%a in (!old! %*) Do (
Set "#=%%~a"
For %%b in (!new!) Do (
If /I "!#!" EQU "%%~b" (Set "#=")
)
REM Prefix:
If DEFINED # (Set "new=!#!;!new!")
REM Append:
REM If DEFINED # (Set "new=!new!;!#!")
)
EndLocal & For /F "tokens=2 delims=:" %%a in ("%0") Do Set "%%a=%new%"
Goto :EOF
:: END SCRIPT ::::::::::::::::::::::::::::::::::::::::::::::::::::
Frank