Find latest file created having specific pattern and to search certain pattern

Had a requirement in unix -> To find latest file created after midnight having specific pattern and to search certain pattern in it.

Files are in folder : demo_dir
File names:  (i.e. file name pattern *demo_file*)
abc_demo_file_yyyymmdd.log
abc_demo_file_yyyymmdd.err
Search pattern : fail

So the requirement is –
In unix folder demo_dir find latest file created after midnight with name *demo_file* having word fail in it

Code to find files :

Explanation :

  • List files (-1 list one file per line )

          -exec ls -1rt “{}” +

  • Get latest 2 files (this will select .log as well as .err file as given in requirement)

          tail -2

  • Search for pattern fail

(-i will search for word by ignoring case
-h will Suppress the prefixing of file names on output)

        xargs grep -ih fail

Vikram Pawar

Vikram Pawar

Coder by passion..... Thirsty for knowledge, challenges & most importantly innovation. Working with BNP Paribas

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *