0

I need to extract log messages for a certain timeframe from a log file. following does not work. Please help

hour=`date +%H`
hour=`expr $hour - 1`
echo $hour
start1=$hour":00:00"
start="$start1"
end1=$hour":59:59"
end="$end1"

awk '$0 >= $start && $0 <= $end' server.log

But the following command works from the command line awk '$0 >= "11:00:00" && $0 <= "11:59:59"' server.log

1 Answers1

2

You are reading the variable wrong with awk. Here is one way to read them

awk '$0 >= s && $0 <= e' s="$start" e="$end" file

You should also not use old and out dated backtics, but use parentheses like this:

hour=$(date +%H)

To remove one hour, do

hour=$(date +%H -d 1h)

To get minutes:

date +%H":00:00" -d 1h
11:00:00
date +%H":59:59" -d 1h
11:59:59

And all in one go:

awk '$0>=s && $0<=e' s='$(date +%H":00:00" -d 1h)' e='$(date +%H":59:59" -d 1h)' file

Ref EDs comment:

awk -v s='$(date +%H":00:00" -d 1h)' -v e='$(date +%H":59:59" -d 1h)' '$0>=s && $0<=e' file
Jotne
  • 40,548
  • 12
  • 51
  • 55
  • 1
    Is there some programming language out there where initializing variables at the end of the program is the natural way of doing things? I've been seeing a few people do this in awk lately and I'm just trying to figure out where the idea is coming from that it's better to init variables AFTER the text of the program than before it. In awk the 2 approaches are not even equivalent since variables init-ed after the script will be uninitialized in the BEGIN so it's not just hard to read, it introduces non-obvious complexity and potential bugs. – Ed Morton Jul 11 '14 at 00:14
  • Why should people not use backticks, is there any actual disadvantage, other than it looking ambiguous maybe. –  Jul 11 '14 at 07:28
  • @Jidder Do a search for it, or read post like this: http://stackoverflow.com/questions/4708549/shell-programming-whats-the-difference-between-command-and-command But in general its more easy to read and better with nesting. – Jotne Jul 11 '14 at 07:55