Bash: Assign output of a command to a variable
I have a nice bit of code to convert hh:mm:ss into seconds like this:
Code:
jonke@charlie:~$ echo "1:01:0" | sed -E 's/(.*):(.+):(.+)/\1*3600+\2*60+\3/;s/(.+):(.+)/\1*60+\2/' | bc How can I assign this to a variable? I've tried: Code:
jonke@charlie:~$ ST="1:01:0" | sed -E 's/(.*):(.+):(.+)/\1*3600+\2*60+\3/;s/(.+):(.+)/\1*60+\2/' | bc |
I think you still need the echo command to be there. Something like:
ST= $(echo.........|bc) |
Panic over guys and gals - I have real trouble with bash, don't use it ofetn enough but I finally figured out this, use a function
Code:
seconds(){ |
I would use awk, something like this:
Code:
echo $1 | awk -F: ' NF==3 { print ($1*3600 + $2*60 + $3) } NF==2 { print ($1*60 + $2) }' |
No need to use sed/bc when GNU coreutils can already parse and convert dates...
Code:
HMS="1:01:00" |
Quote:
Code:
VAR="1:01" |
Quote:
BTW I've used your first example! But I've changed back to sed, I don't want to put in the hours every time. |
A solid alternative to
Code:
A=(${VAR//:/ }) Code:
IFS=":" read -a A <<< $VAR A work-around is to prefix it with 10# Code:
sec=$(( 10#${A[-1]} + 60 * 10#${A[-2]} + 3600 * 10#${A[-3]} )) |
All times are GMT -5. The time now is 07:21 PM. |