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:

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

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

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

FOUR:
$ 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

Share and Enjoy

  • Twitter
  • Facebook
  • Google Plus
  • Email
  • RSS
Tagged with: , , , , , , , , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe

  

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