1

I have two log files namely, Log_1.log Log_2.log which contains the following data.

Log_1.log:
Apr 10 02:07:20  Data 1
May 10 04:11:09  Data 2
June 11 06:22:35  Data 3
Aug 12 09:08:07  Data 4

Log_2.log
Apr 10 09:07:20  Data 1
Apr 10 10:07:10  Data 2
Jul 11 11:07:30  Data 3
Aug 18 12:50:40  Data 4

I am using the following code to extract the data between starttime and endtime.

sort -t' ' -k1,1M -k2,3n log_1.log log_2.log | sed -n '/Apr 10 02:07:20/,/Jul 11 11:07:30/p'

and my output is

Apr 10 02:07:20  Data 1
Apr 10 09:07:20  Data 1
Apr 10 10:07:10  Data 2
May 10 04:11:09  Data 2
June 11 06:22:35  Data 3
Jul 11 11:07:30  Data 3

is it possible for me to get the output in below format?

Log_1.log
Apr 10 02:07:20  Data 1
May 10 04:11:09  Data 2
June 11 06:22:35  Data 3
Log_2.log:
Apr 10 09:07:20  Data 1
Apr 10 10:07:10  Data 2
Jul 11 11:07:30  Data 3

Please help. Thanks in Advance

Vedh
  • 93
  • 1
  • 10

1 Answers1

2

Instead of giving both files as input to the command at the same time, run the command once for each file.

for file in log_1.log log_2.log; do
    echo "$file:"
    sort -t' ' -k1,1M -k2,3n $file | sed -n '/Apr 10 02:07:20/,/Jul 11 11:07:30/p'
done
raimue
  • 4,322
  • 1
  • 21
  • 31
  • Thanks for the answer. The code works fine when the dates entered are present in the log file. If I enter the dates like, `'/Jan 01 10:00:00/,/Jun 1 12:00:/p'` the result is null, since such dates are not in log file. Is there a solution to start from the nearest next date if the entered startime is not present in the log file?The same for the end date. – Vedh Jun 23 '16 at 05:27
  • These tools are just text processing tools. Once you need more logic like this, you need to write a more elaborated script. Especially the month names need to be converted first, as they cannot be compared alphabetically. – raimue Jun 23 '16 at 09:47
  • For example, look at these questions: [Q1](https://unix.stackexchange.com/questions/120831/grep-for-range-of-numbers) [Q2](https://stackoverflow.com/questions/7575267/extract-data-from-log-file-in-specified-range-of-time) – raimue Jun 23 '16 at 09:47
  • Thanks. In the log files, there are four feilds, that is, month date time data. So If I use $1, it refers date, $2 refers time and $3 for data. Can i combine month, date and time in a single token? – Vedh Jun 23 '16 at 11:02