2

I'm trying to find a specific line from the newest file I have in subfolders. Files have the same name. So structure is like:

  • Folder
    • SubFolder1
      • filename.xml
    • SubFolder2
      • filename.xml

I'm using grep to have the line

grep -r "mySubString" folder/

I've try using find to sort files as proposed here. But I don't know how to combine both to get just the line from the newest file.

Thanks for your help.

  • it is not clear whether you want to run grep on the latest file, even if it finds nothing, or whether you want the output from the latest file where grep finds a match. – AFH Oct 7 '14 at 9:49
  • Thanks AFH for your comment. I want to run the grep in the newest file. – Mario Levrero Oct 7 '14 at 10:12
  • In that case @ap0 gives the neatest answer below, but it will need modification if you want to know which of the files the string came from. – AFH Oct 7 '14 at 10:20
1
find . -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d" "

This will return the latest file created from the directory you are running this command from and all sub directories. If you want so search in a specific directory chane . to the directory path.

to grep for the content of this file:

cat `find . -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d" "` | grep "mySubString"

Edit: I am not sure. I tryed this my self quickly and it worked. I created a test file and used this command. It worked for me. If there is a problem, please let me know.

1

zsh:

grep pattern **/*(.om[1])

om orders by modification date and . is a qualifier for regular files.

GNU find:

grep pattern "$(find -type f -printf '%T@ %p\n'|sort -n|tail -n1|cut -d' ' -f2-)"

%T@ is modification time and %p is pathname.

BSD:

grep pattern "$(find . -type f -exec stat -f '%m %N' {} +|sort -n|tail -n1|cut -d' ' -f2-)"

%m is modification time and %N is pathname.

bash 4:

shopt -s globstar;grep pattern "$(ls -dt **|head -n1)"

This includes directories and can result in an argument list too long error.

  • This is right also, I can't upvote due to my low reputation. – Mario Levrero Oct 7 '14 at 13:45

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.