user3438349
user3438349

Reputation: 67

Issue: iteration in sh

I'm kind new in sh and I would like to make iteration on an array.

declare -a NumPack
NumPack=(88 88 454 454 65 874 874 21 21)
for carton in $NumPack
do
echo "carton: $NumPack"
done

I would like to search for the same numbers like the first one. My program would return 2 for the first number(88), 3 for the next number(454), 1 for the next (65).

I also have a second array with the numbers of articles which contain those pack above.

declare -a NumArt
NumArt= (ZZZZ CCDE AZDSDS SDSEE AAAZE TTGYH DFDF ARFFF TRUCC TOUCKC)

the articles

(ZZZZ,CCDE) belong to the pack 88 
the articles (AZDSDS,SDSE,AAAZE) belong to the pack 454, 
the article TTGYH belong to the pack 65, 
the articles (DFDF,ARFFF) belong to 874, and the rest to 21.

I had to push those lines in a files by pair of 4. I had to avoid to split a pack. Every articles belong to a pack must be in a one file.

So the

88 => file1
  454,65 => file2
  (874,21) =>file3.

thanks for your help

Upvotes: 2

Views: 123

Answers (1)

damienfrancois
damienfrancois

Reputation: 59070

I am assuming you are wanting to learn rather than solve the problem (in which case I'd advocate the use of the uniq -c command)

See the following script:

declare -a NumPack
NumPack=(88 88 454 454 65 874 874 21 21)
declare -A res
for carton in "${NumPack[@]}"
do
echo "carton: $carton"
res[$carton]=$((${res[$carton]}+1))
done
echo ${res[@]}

I create an associative array named res to hold the result. Note the proper way to iterate: for carton in ${NumPack[@]} and the use of $(( )) for algebraic expressions.

Upvotes: 1

Related Questions