1

I am trying to extract time range from a logfile by passing shell variables in awk. This is how my log file is.

2014-11-24 12:58:59.290 1.1.1.1  etc..
2014-11-24 13:58:59.290 2.2.2.2  etc..
2014-11-24 14:58:59.290 3.3.3.3  etc ..
2014-11-24 12:58:59.290 4.4.4.4  etc.. 
2014-11-24 15:58:59.290 4.4.4.4  etc..

Suppose I want to extract time range between 12 hours and 13 hours. Here is the bash script I have written.

stime=12
etime=13
date_=2014-11-24

awk 'BEGIN {
          a='$stime';b='$etime';d='$date_'; FS="[: ]"
       }

      { 
  if ( $1 == d && $2 >= a && $2 < b )
      print $1 $2 $3
      }'  logfile.txt

My output should look like this.

 2014-11-24 12:58:59.290 1.1.1.1  etc..  
 2014-11-24 12:58:59.290 4.4.4.4  etc..  

I don't see any output nor any errors. I don't know what's is going wrong. Any help with this would be appreciated. Thank you

  • ... also, what is ; doing inside your FS? – steeldriver May 17 '16 at 1:12
2
stime=12
etime=13
date=2014-11-24

awk -v a="$stime" -v b="$etime" -v d="$date" -F "[: ]+" '
  { 
  if ( $1 == d && $2+0 >= a && $2+0 < b )
      print $1,$2,$3
  }'  logfile.txt

This produces the output:

2014-11-24 12 58
2014-11-24 12 58

Notes:

  1. FS="[: ];" causes the field separator to be set to a colon or space followed by a semicolon. That combination never occurs in the input file.

  2. In the original code, the assignment d='$date_'; resulted in d having the value of 1979. That is because, when introduced in awk code, the expression 2014-11-24 is interpreted as a numerical expression requiring subtraction.

  3. It is good practice to transfer shell variables to awk using the -v option. Both the shell and awk can require proper quoting and the -v option allows us to deal with these quoting issues one at a time.

  4. awk is capable of doing either numeric or alphabetic comparison depending on context. By adding +0 in the code, we assure that awk is doing numeric comparison.

  • It worked. I have a question. What is that +0 after $2? – Swatesh Pakhare May 17 '16 at 1:21
  • Very good. The +0 tells awk to add zero to the value of $2. This forces awk to treat $2 as a number. – John1024 May 17 '16 at 1:24
  • @SwateshPakhare The answer shows an example of a case where the +0 was essential. – John1024 May 17 '16 at 2:07

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.