Window batch / DOS script to remove duplicate words in a string [closed]

你说的曾经没有我的故事 提交于 2019-12-13 09:05:29

问题


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%"


来源:https://stackoverflow.com/questions/35486995/window-batch-dos-script-to-remove-duplicate-words-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!