Register
It is currently Wed Apr 16, 2014 1:41 pm

Decrementing an array value


All times are UTC - 6 hours


Post new topic Reply to topic  [ 2 posts ] 
Author Message
 PostPosted: Thu Feb 04, 2010 10:56 am   

Joined: Thu Feb 04, 2010 6:56 am
Posts: 2
Hi,

I'm trying to decrement the values contained in an array. I'm reading a file which has a list of indices and for each one I want to decrement the value held in the array at that index. Seems simple but I'm not sure what I'm doing wrong.

Code:
#!/bin/bash

instanceFile=$1
solutionFile="${instanceFile/.txt/.sol}"

#echo "Inst: $instanceFile, Sol: $solutionFile"
capacity=$(head -n 1 $instanceFile)

binItems=()
while read -r size amount; do
   binItems[$size]=$amount
done < <(tail -n +4 $instanceFile)

# Just verifying that the array is instantiated properly
for i in ${!binItems[*]}; do
   echo "[$i] ${binItems[$i]}"
done

while read -d " " size; do
   echo -n "Pre: ${binItems[$size]} "
   binItems[$size]=$((${binItems[$size]}-1))
   echo "Post: ${binItems[$size]} "
done < $solutionFile


The instance file is:
100
26
23
3 1
6 2
8 2

The solution file contains:
3 8
6 8
6

The error I'm getting from bash is:
-1")syntax error: invalid arithmetic operator (error token is "

I can't see any errors with the way I'm doing the arithmetic or the array assignment? Can anyone shed some light on this?

Thanks,
Alastair


Top
 Profile  
 PostPosted: Fri Feb 05, 2010 3:24 am   

Joined: Thu Feb 04, 2010 6:56 am
Posts: 2
It seems as if the problem was carriage returns corrupting my data.

Changing the assignment in the first loop to:
Code:
binItems[$size]=${amount//$'\r'}

sorts the problem by using bash's parameter expansion to trim off the offending character.


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Bing [Bot] and 5 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP