deepak Singla
deepak Singla

Reputation: 1

How to remove duplicate comma separated values from variable using batch file?

Want to remove the duplicate values from machines variable in below batch file:

@echo off
set machines=node1,node2,node3,node2,node4,node1,node7,node6,node4

Expected output:

node1,node2,node3,node4,node6,node7

Upvotes: 0

Views: 199

Answers (2)

Paul Houle
Paul Houle

Reputation: 735

A short way to do it (this doesn't sort the machines variable, only removes the duplicates):

@echo off& setlocal EnableDelayedExpansion
set machines=node1,node2,node3,node2,node4,node1,node7,node6,node4

set "tmac=,"& for %%a in (%machines%) do if "!tmac:,%%a,=!"=="!tmac!" set "tmac=!tmac!%%a,"
set machines=%tmac:~1,-1%

Upvotes: 0

user6811411
user6811411

Reputation:

One way to accomplish your task:

  • Iterate the machines with a for and set them to an array,
    this overwrites doublette entries.
  • Read the (alpha sorted) array back and store in the original variable (requires delayed expansion).

:: Q:\Test\2018\09\20\SO_52417320.cmd
@Echo off & Setlocal EnableDelayedExpansion
Set machines=node1,node2,node3,node2,node4,node1,node7,node6,node4

:: clear array machine[], then fill it
For /f "tokens=1 delims==" %%M in ('Set machine[ 2^>Nul') do Set "%%M="
For %%M in (%machines%) do Set "machine[%%M]=%%M"
Set machine[
Echo:    
Set "machines="
For /f "tokens=2 delims==" %%M in ('Set machine[') do Set "machines=!machines!,%%M"

Echo:%machines:~1%

Sample output:

> SO_52417320.cmd
machine[node1]=node1
machine[node2]=node2
machine[node3]=node3
machine[node4]=node4
machine[node6]=node6
machine[node7]=node7

node1,node2,node3,node4,node6,node7

Upvotes: 1

Related Questions