Grep in newest file

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.

Mario Levrero

Posted 2014-10-07T09:28:44.833

Reputation: 123

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 – 2014-10-07T09:49:15.913

Thanks AFH for your comment. I want to run the grep in the newest file. – Mario Levrero – 2014-10-07T10:12:40.487

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 – 2014-10-07T10:20:46.113

Answers

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

Posted 2014-10-07T09:28:44.833

Reputation: 1 180

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

Posted 2014-10-07T09:28:44.833

Reputation: 34 501

This is right also, I can't upvote due to my low reputation. – Mario Levrero – 2014-10-07T13:45:40.510