0

How can I read a line from a file into two variables: one variable for the last field, and the the other variable for the other fields?

For example, I have a file:

hello world! 10s
It is a good day. 4m
...

I would like to read each line into two variables: one variable contains the time interval at the end of the line, and the other variable contains the fields before it. I was wondering how to do it; this is as far as I have gotten:

while read line 
do
    ...  # split $line into $message and $interval
    myprogram "$message" "$interval"
done < "$inputfile" 
K7AAY
  • 3,816
  • 4
  • 23
  • 39
Tim
  • 101,790

1 Answers1

3

As long as the interval contains no whitespace this should work:

#!/bin/bash

input=/path/to/input

while read -r line; do
    message=${line% *}
    interval=${line##* }
    echo "$message"
    sleep "$interval"
done < "$input"

${line% *} Will strip everything after the last space character

${line##* } Will strip everything before the last space character

jesse_b
  • 37,005