2

In the following command, how can I get the file names based on its timestamp

$ grep "exit 0" a*
a1.txt:+ exit 0
a2.txt:+ exit 0
a3.txt:+ exit 0
a4.txt:+ exit 0
a5.txt:+ exit 0

$ ls -latr 
-rw-r--r-- 1 user grp  83046 Oct 27 06:46 a5.txt
-rw-r--r-- 1 user grp  68108 Oct 27 07:59 a1.txt
-rw-r--r-- 1 user grp 159792 Oct 27 12:35 a2.txt
-rw-r--r-- 1 user grp 225703 Oct 27 16:41 a3.txt
-rw-r--r-- 1 user grp 246782 Oct 27 20:17 a4.txt

As you see the above output, I am not getting the output based on the timestamp the file was created. Is there any way to achieve it?

3 Answers 3

3

If none of the file names contain space, tab, newline (and $IFS has not been modified), ?, *, [ characters or are called -, this should do it:

grep -- "exit 0" $(ls -tr a*)

$() is called command substitution. Your shell will first run ls -tr, then split+glob its output to make up the list of files passed to your grep command.

4
  • Omni, I noticed that your command also displays the output from unmatched files also. For eg. I am trying to grep on a*.txt, but it gives the output on b*txt too. why is it so?
    – janani
    Commented Oct 28, 2014 at 20:44
  • Sorry it was my bad. Instead of doing, grep "exit 0" $(ls -tr a*), i was doing - grep "exit 0" a* $(ls -tr)
    – janani
    Commented Oct 28, 2014 at 20:49
  • @Gilles, -- doesn't protect against a file called -. Commented Oct 29, 2014 at 7:30
  • @janani I'm glad you caught that. I'd meant to include a* in my command to match your example. I'll update the answer for future generations. Commented Oct 29, 2014 at 12:51
2

With the zsh shell, you can affect the order of globs with glob qualifiers.

grep 'exit 0' a*(.Om)

Om is to reverse o⃞rder by m⃞odification time. I also added .⃞ to select only regular files (not directories or pipes or devices or symlinks...).

-2

Thanks Omni. Even the following way, I am able to achieve this. Of course urs is the simple one. thanks a lot

       grep -H "exit 0" /opt/ctmagent/ctm/sysout_archives/141027/d_dms_btch_alrt_ifm_scp_ksh* | awk -F":" '{system("ls -latr "$1"")}'
1
  • 1
    That runs one ls per file, so is not going to do anything wrt sorting. That also interprets the file name as shell code so is very dangerous. Commented Oct 28, 2014 at 20:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .