1

I am new in bash scripting and I need help in my task... I have an array :

arr=( one two tree four five six seven one  four  nine one  two  one  ten )

I need to change it on the rule : If element repeated first time add 1 to the end, if twice - 2.

Expecting result:

arr=( one two tree four five six seven one1 four1 nine one2 two1 one3 ten )

My code :

for i in ${!arr[*]}
do
    k=1
    for j in ${!arr[*]}
        do
        if [[ ( ${arr[$i]} = ${arr[$j]} ) && ( $i > $j )  ]] ;then
            arr[$i]=$(echo ${arr[$j]}$k)
            ((j++))
            ((k++))
        fi
    done
    echo ${arr[$i]}
    ((i++))
done

Please, give me advice how to resolve this task...

0

1 Answer 1

2

Use an associative array to hold the current count for each word.

declare -A count
for i in ${!arr[*]}
do
    if [[ -n "${count[${arr[$i]}]}" ]]
    then 
        ((count[${arr[$i]}]++))
        arr[$i]=${arr[$i]}${count[${arr[$i]}]}
    else
        count[${arr[$i]}]=0
    fi
done
Sign up to request clarification or add additional context in comments.

8 Comments

all count will be 1 in your solution
Why? ((count[$arr[$i]]++)) increments the count each time it's used.
when I make echo ${count[*]} it holds only 1 1 1 .....
I fixed the problems.
A shorter version: for i in ${!arr[*]}; do ((count[${arr[$i]}]++)) && arr[$i]+=$((count[${arr[$i]}]-1)); done
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.