Oneliners for Removing the duplicates in your $PATH

Hello Bash Coders.

In this article I will show you how to remove the duplicates in your PATH environment variable.

This is how you do it with AWK:

$ echo -n $PATH | awk -v RS=: -v ORS=: '!arr[$0]++'

$ echo -n $PATH | awk -v RS=: -v ORS=: '{ if (!arr[$0]++) { print $0 } }'

$ PATH=`echo -n $PATH | awk -v RS=: '{ if (!arr[$0]++) {printf("%s%s",!ln++?"":":",$0)}}'`

$ PATH=`awk -F: '{for (i=1;i<=NF;i++) { if ( !x[$i]++ ) printf("%s:",$i); }}' <<< $PATH`

Do it with sed:

$ PATH=$(echo $PATH | sed ':b;s/:\([^:]*\)\(:.*\):\1/:\1\2/;tb;s/^\([^:]*\)\(:.*\):\1/:\1\2/')

With tr, sort and uniq:

$ PATH=`echo $PATH | tr ':' '\n' | sort | uniq | tr '\n' ':'`

With perl:
$ PATH=`perl -e '@A=split(/:/,$ENV{PATH});%H=map {$A[$#A-$_]=>$#A-$_} (0..$#A);@A=join(":",sort{$H{$a} <=> $H{$b} }keys %H);print "@A"'`

Do not forget to export your PATH, after this:

$ export PATH

Tagged with: , , , , , , , , , , ,
Posted in The Linux and Unix Articles!
One comment on “Oneliners for Removing the duplicates in your $PATH
  1. Sandor says:

    The script with tr, sort, uniq is definitiv wrong: it changes the order of the items; it can be (and is) relevant.

Leave a Reply

Your email address will not be published. Required fields are marked *




Subscribe to get the latest Linux news and how to guides directly on your e-mail!