Window batch / DOS script to remove duplicate word

2019-09-24 04:58发布

问题:

Can anyone help me with window batch / DOS script to remove in a string.

If the string is -

test1 test2 test1 test3 test2 test3

I need a script to display as

test1 test2 test3

回答1:

the same way, you would do it manually: take every element, check if it already is in output, if not, append it:

@echo off
setlocal enabledelayedexpansion
set "string=test1 test2 test1 test3 test2 test3"
set "newstring="
for %%i in (%string%) do (
  echo !newstring!|findstr /i "\<%%i\>" >nul || set "newstring=!newstring! %%i"
)
echo %newstring:~1%

(Note: remove /i if you want it case sensitive)

edited to handle complete words instead of (possible) substrings.



回答2:

There are several ways to do this; for example:

@echo off
setlocal EnableDelayedExpansion

set "in=test1 test2 tes test1 test3 test test2 test3"


rem 1- Insert the word if it is not in the output already
set "out= "
for %%a in (%in%) do (
   if "!out: %%a =!" equ "!out!" set "out=!out!%%a "
)
echo "%out:~1,-1%"


rem 2- Remove each word from output, then insert it again
echo/
set "out= "
for %%a in (%in%) do (
   set "out=!out: %%a = !"
   set "out=!out!%%a "
)
echo "%out:~1,-1%"