FreeKB - Bash Shell Scripting remove duplicate values from a variable
Bash Shell Scripting - remove duplicate values from a variable

Let's say you have a variable (foo in this example) with dupliate values (bar in this example).

foo="hello world bar bar bar bar bar"

 

The following command will remove the duplicate values from the variable (credit goes to this Stack Overflow post).

echo "$foo" | awk '{for (i=1;i<=NF;i++) if (!a[$i]++) printf("%s",$i,FS)}{printf("\n")}'

 

The result will be:

hello world bar

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 21cbc in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |