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.

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,318
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
  • 42,502
  • 8
  • 126
  • 159