FreeKB - Remove duplicate values from a variable in Linux BASH
Remove duplicate values from a variable in Linux BASH

Home > Search


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 in the box below so that we can be sure you are a human.




Comments