1

I have a file

a 10:10 10:30
b 12:15 13:15
c 16:54 17:54

and I need to enter interval for example 10:15 so my output should be a 10:10 10:30 How I need to do that using awk?

  • 1
    Please do not cross post: stackoverflow.com/questions/29846296/shell-intervals – fedorqui Apr 24 '15 at 11:43
  • 1
    Why awk? It is not very easy in awk but is trivial using other tools. Also, please delete one of the two duplicate questions you have posted. Keep either this one or the one on Stack Overflow. – terdon Apr 24 '15 at 11:48
  • 2
    You could try: awk -v myts="10:15" '{if ($2 <= myts && $3 >= myts) print $2,$3}' infile – don_crissti Apr 24 '15 at 11:59
  • @don_crissti maybe awk -v myts="10:15" '$2 <= myts && $3 >= myts' infile – FloHimself Apr 24 '15 at 12:07
  • 1
    @FloHimself well, now that I've seen what you and don_crissti came up with, I'd use awk :) I had thought the numerical comparison would choke on 10:13 and was instead thinking of using date -d 10:15 +%s to convert to seconds and compare that way. – terdon Apr 24 '15 at 14:19
-1

1) Comparing hours and minutes separately:

awk -vt="10:15" -F"[: ]" '
  BEGIN{split(t,a,":")}
  $2<=a[1]&&$3<=a[2]&&$4>=a[1]&&$5>=a[2]
' <<_INPUT_
a 10:10 10:30
b 12:15 13:15
c 16:54 17:54
_INPUT_
a 10:10 10:30

2) Converting hours to minutes:

awk -vt="13:00" -F"[: ]" '
  BEGIN{split(t,a,":");t=60*a[1]+a[2]}
  60*$2+$3<=t&&60*$4+$5>=t
' <<_INPUT_
a 10:10 10:30
b 12:15 13:15
c 16:54 17:54
_INPUT_
b 12:15 13:15

3) Using a function:

awk -vt="17:15" '
  function f(s){split(s,a,":");return(60*a[1]+a[2])}
  f($2)<=f(t)&&f($3)>=f(t)
' <<_INPUT_
a 10:10 10:30
b 12:15 13:15
c 16:54 17:54
_INPUT_
c 16:54 17:54
  • Would you mind commenting on the downvote? I'd be happy to improve my answer and learn something new. But as far as I can tell, it answers the OPs question. – mschilli Jun 30 '15 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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