Or, as a rule, how to remove an item from a colon separated list in a Bash environment variable?
I thought I saw an easy way to do this many years ago, using more advanced forms of expanding the Bash variable, but if so, I lost it. A quick Google search showed surprisingly few relevant results, and none of them would call "simple" or "elegant." For example, two methods using sed and awk, respectively:
PATH=$(echo $PATH | sed -e 's;:\?/home/user/bin;;' -e 's;/home/user/bin:\?;;') PATH=!(awk -F: '{for(i=1;i<=NF;i++){if(!($i in a)){a[$i];printf s$i;s=":"}}}'<<<$PATH)
There is nothing simple? Is there anything similar to the split () function in Bash?
Update:
It seems like I need to apologize for my intentionally vague question; I was less interested in solving a particular use case than provoking a good discussion. Fortunately, I got it!
There are very smart methods here. In the end, I added the following three functions to my toolbox. The magic happens in path_remove, which is largely based on Martin Yorke's ability to use the awk RS variable.
path_append () { path_remove $1; export PATH="$PATH:$1"; } path_prepend () { path_remove $1; export PATH="$1:$PATH"; } path_remove () { export PATH=`echo -n $PATH | awk -v RS=: -v ORS=: '$0 != "'$1'"' | sed 's/:$//'`; }
The only real breakthrough in this case is using sed to remove the back colon. Given how fair the rest of Martin’s decision is, I completely agree to live with it!
Related Question: How do I manipulate $ PATH elements in shell scripts?
bash shell path variable-expansion list-processing
Ben Blank Dec 15 '08 at 23:19 2008-12-15 23:19
source share