How to list files using the sort command, but not the ls -lrt command

I am writing a shell script to check for some parameters, such as errors or exceptions inside the log files that have been generated over the past 2 hours in the / var / log directory. So this is the command I use:

find /var/log -mmin -120|xargs egrep -i "error|exception" 

It displays a list of file names and its corresponding parameters (errors and exceptions), but the list of files does not match the time sequence. I mean, the output is similar to this (sequence):

 /var/log/123.log:RPM returned error /var/log/361.log:There is error in line 1 /var/log/4w1.log:Error in configuration line 

But the sequence in which these 3 log files were created is different.

 /var/log>ls -lrt Dec24 1:19 361.log Dec24 2:01 4w1.log Dec24 2:15 123.log 

So, I want the result to be in the same sequence, I mean this:

 /var/log/361.log:There is error in line 1 /var/log/4w1.log:Error in configuration line /var/log/123.log:RPM returned error 

I tried this:

 find /var/log -mmin -120|ls -ltr|xargs egrep -i "error|exception" 

but it does not work. Any help on this is really appreciated.

+5
source share
2 answers

You can add the modified time with the -printf argument to find , then sort , and then remove the changed time with sed :

 find /var/log -mmin -120 -printf '% T@ :%p\n' | sort -V | sed -r 's/^[^:]+://' | xargs egrep -i "error|exception" 
  • find ... -printf '% T@ :%p\n' prints every found file ( %p ) added by seconds since the UNIX era ( % T@ , for example, 1419433217.1835886710 ) and a colon delimiter ( : , each of which is a new line ( \n ).

  • sort -V sorts files naturally by modification time because it is at the beginning of each line (for example, 1419433217.1835886710:path/to/the/file ).

  • sed -r 's/^[^:]+://' takes each line in the format 123456789.1234:path/to/the/file and removes the modification time, leaving only the path to the file path/to/the/file

0
source

If your names do not have special characters (for example, newlines, etc.), you need another xargs call:

 find . -type f -mmin -120 | xargs ls -tr | xargs egrep -i "error|exception" 

Or, if your file names contain the specified special characters:

 find . -type f -mmin -120 -print0 | xargs -0 ls -tr | xargs egrep -i "error|exception" 
+1
source

Source: https://habr.com/ru/post/1209841/


All Articles