Question

I want to go over a file and read two words at a time. So I thought I could do what the for loop would do to read a word at a time, and continuously go over the file.

PS: This is what the script does: reads over a file that has working hours (start time and finish time, there could be more that one pair for the day) and gives a total time for the month.

I want to read two words at a time to make it much easier to figure out the number of worker hours for each day. Specially since hours are entered like 12:16 and I have to parse for hour and minute of each entery

EDIT: text file with hours looks like this: 8:50 15:60 9:9 13:41 14:23 18:40 10:00 18:00

Notice how the spacing between each entry doesn't have to be exact, and how you can have more than 2 times for the same day since you can leave work and come back

And also I don't have much code written since I couldn't figure how I was going to do the code.

Was it helpful?

Solution

All for loops can be implemented as while loops:

WORD_PAIRS=(a b c d e f g h)
COUNT=${#WORD_PAIRS[@]}
i=0
while [[ $i -lt $COUNT ]]
    do
    WORD1=${WORD_PAIRS[$i]}
    WORD2=${WORD_PAIRS[$i + 1]}
    echo $WORD1 $WORD2
    i=$(($i + 2))
done

Output:

a b
c d
e f
g h

OTHER TIPS

If you go with the shell's builtin definition of a word, which is each continuous string of characters other than "$IFS", you can read a file one word at a time like this:

for word in $(<file); do
  action "$word"
done

To operate on two words at a time, you need to accumulate:

pair=()
for word in $(<file); do
  pair+=("$word")
  if (( ${#pair[@]} % 2 == 0 )); then
    action "${pair[@]}"
    pair=()
  fi
done
# Decide if you want to handle the scenario where there's a final word
# … action "${pair[@]}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top