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" 
  • Will the interval ever contain white space? – Jesse_b Nov 8 at 23:02
  • Thanks. The time interval will be used as argument to sleep. If sleep accepts an argument with a space within it, then yes; otherwise, no. – Tim Nov 8 at 23:04
  • Obligatory unix.stackexchange.com/q/169716/117549 – Jeff Schaller Nov 8 at 23:44
  • @JeffSchaller Could you tell me how I should rewrite my while loop? I have looked at the link – Tim Nov 8 at 23:48
  • It's apparent that reading into variables is not your final destination; there might be other/better ways to accomplish your goal, if we knew what it was. – Jeff Schaller Nov 8 at 23:51
up vote 3 down vote accepted

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

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.