bash array question

Nathan England nathan at paysonlinux.org
Mon Jun 20 11:35:35 MST 2011


I use a lot of arrays in bash, but I have never before needed to modify the
contents of the array once I had created it, but now I need to. I followed
the tutorial on this page:
http://www.thegeekstuff.com/2010/06/bash-array-tutorial/

and it gives an example of

#########################
$cat arraymanip.sh
#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux'
'HP-UX');

echo ${Unix[@]/Ubuntu/SCO Unix}

$./arraymanip.sh
Debian Red hat SCO Unix Suse Fedora UTS OpenLinux
##################################

So I decided to try creating a new array and replacing what I don't want
with nothing by doing the following:

tmpArray=( ${Unix[@]/deleteme/} )
Unix=("${tmpArray[@]}")

So far this has worked great, but I've run into a problem. Say I have 'HP'
and 'HP-UX' in my array and I want to remove the 'HP', so I would do
tmpArray=( ${Unix[@]/HP/} )
Unix=("${tmpArray[@]}")

at first glance this worked fine, until I realized that now, instead of
'HP-UX' in my array, I now have '-UX'
It seems to replace all instances, which is what I want, but the pattern
matches even in this example, which is what I don't want.

Following his tutorial, I would need to know the number of the element in
the array I want to delete, but my problem is there may be 10 instances in
the array of 'HP' and I want to delete them all, so I would need to loop
through it over and over until all instances are gone. Also, the elements
inserted into the array are variables and I don't necessarily know the order
of the elements, so I cannot just tell it to delete element X like in his
example. The array is not static anywhere in my script.

So how do I remove something from an array without having to run through
every element in an array and test for whole matches? My array might be 100
elements large, which can take a LONG time to loop through when I am adding
or removing another hundred items to the array. I liked this pattern replace
because it was fast, I don't want to lose my speed now!

Thanks for your help.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.PLUG.phoenix.az.us/pipermail/plug-discuss/attachments/20110620/1c7f4bf2/attachment.html>


More information about the PLUG-discuss mailing list