3

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.

Mario Levrero
  • 133
  • 1
  • 6
  • 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 07 '14 at 09:49
  • Thanks AFH for your comment. I want to run the grep in the newest file. – Mario Levrero Oct 07 '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 07 '14 at 10:20

2 Answers2

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.

ap0
  • 1,308
  • 7
  • 14
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.

Lri
  • 40,894
  • 7
  • 119
  • 157