2

the string IP include some IP address numbers as the following example

echo ${IP[*]}

192.9.200.1 192.9.200.2 192.9.200.3

is it possible to remove some IP address number from the list ( using ksh shell ) ?

for example

I want to delete the IP - 192.9.200.2 from the string "IP"

so I will get the following

echo ${IP[*]}

192.9.200.1 192.9.200.3
1
IP=(192.9.200.1 192.9.200.2 192.9.200.3)
remove=192.9.200.2
new=()
for ip in "${IP[@]}"; do [[ $ip != $remove ]] && new+=($ip); done
echo "${new[*]}"
192.9.200.1 192.9.200.3

Or

for ((i=0; i<${#IP[@]}; i++)); do
    [[ ${IP[i]} == $remove ]] && unset IP[i]
done
echo "${IP[*]}"                                                                 
192.9.200.1 192.9.200.3
1

It's possible, but since they are not hashed, you have to iterate over each element:

i=0
for item in "${IP[@]}"; do
    if [ "$item" = 192.9.200.2 ]; then
        unset IP["$i"]
        break # Remove this if the item could appear more than once
    fi
    let i++
done
  • Is the separate i variable used due to a specific ksh version? For now I can only check MirBSD Korn Shell, but there for item in "${!IP[@]}"; do if [ "${IP[item]}" = 192.9.200.2 ]; then unset IP[item]; fi ; done works. – manatwork Jun 23 '13 at 11:24
  • @manatwork I'm not totally sure how portable "${!var[@]}" is in older ksh variants, so I avoided it. – Chris Down Jun 23 '13 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.