1

I want to find file with specific pattern and print the latest file matching the pattern with full path

find ../*.gz -type f -print0 | sort -nr | cut -d: -f2- | head -n 1

How do I print the full path of the same.

As requested by users ls -l:

ls -l
drwxrwxr-x 3 xxx xxx 4096 Jun 27 23:29 fa1caae85
drwxrwxr-x 3 xxx xxx 4096 Jun 27 23:28 ga1c93eda
drwxrwxr-x 3 xxx xxx 4096 Jun 27 23:28 la1cbbh05
drwxrwxr-x 3 xxx xxx 4096 Jun 27 23:08 node_modules
drwxrwxr-x 3 xxx xxx 4096 Jun 27 23:08 _tasks

All top three folders contains require .gz files, however I want to get latest .gz file out of them.

  • @Rahul, yes. I guess my pattern is *.gz – Reddy Jun 28 '16 at 6:49
  • 1
    You do realize that find ../*.gz doesn't make sense, right? – Satō Katsura Jun 28 '16 at 7:06
  • @SatoKatsura, didn't get you. Can you explain plz – Reddy Jun 28 '16 at 7:49
  • @Rahul, I am searching for that file in sub-directories. – Reddy Jun 28 '16 at 7:50
  • @Rahul, yes. I updated the OP with your request – Reddy Jun 28 '16 at 7:56
1

You can do that by using this command,

find "$(pwd)" -type f -name "*.gz" -printf "%T@ %p\n"| sort -n | cut -d' ' -f 2 | tail -n 1
  • it still prints relative path. – Reddy Jun 28 '16 at 9:00
  • @Reddy try updated one – Rahul Jun 28 '16 at 9:12
  • worked out. Thanks. is it head or tail – Reddy Jun 28 '16 at 9:59
  • 1
    @Reddy you have used sort -nr | head -n 1 and I have just used sort -n | tail -n 1, both are one and the same thing. – Rahul Jun 28 '16 at 11:14
  • 1
    #Rahul, missed that one char. I was just wondering myself is it head or tail. Thanks for pointing – Reddy Jun 28 '16 at 12:40
1

Unorthodox approach:

zsh -c 'echo $PWD/**/*.gz(.om[1])'

where

  • () after *.gz means to use so called glob qualifiers, i.e.:
  • . consider only plain files
  • om sort by modification time
  • [1] take only first element

Obviusly if you are already using zsh you don't need to call it with zsh -c.

  • Not using zsh. Looking for bash solutions :) – Reddy Jun 28 '16 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.