grep ouput filepath with file modified date?

12,170

Solution 1

grep itself has no functionality for that. But you can use awk. Use that syntax:

grep -Hr pattern . | awk -F: '{"stat -c %z "$1 | getline r; print r": "$0 }'

That forces grep to print the filenames -H. -r means search recusive in the given directory .. awk's field separator is set to :. The first varibale $1 now contains the filename. awk calls stat -c %z on each filename, which gives the modification time in human readable format. That is saved into the variable r, which is printed in front of each search result.

Solution 2

It turns out you can use find -exec to do this. The following is not a complete example as it does not output quite the format requested.

 find . -exec grep -q set {} \; -exec stat -c "%y %n" {} \;

...

2019-06-03 11:46:14.565890000 -0700 ./bin/tkdiff_helper.sh

2018-04-24 12:00:02.389077000 -0700 ./bin/start_vnc.older 2019-09-04

08:41:49.021891000 -0700 ./bin/calmdpv_2016

...

The second exec only runs if grep finds a match.

-q is to quite grep.

Solution 3

Here is a more understandable alternative using xargs

grep -rl pattern | xargs stat -c %n':'%z | awk -F: '{print $1}'
Share:
12,170

Related videos on Youtube

user3257264
Author by

user3257264

Updated on September 18, 2022

Comments

  • user3257264
    user3257264 over 1 year

    Is it possible to make the grep command to output file paths with file modified date like so:

    12-02-2015 /file/path/to/the/file
    16-02-2015 /file/path/to/the/file
    25-02-2015 /file/path/to/the/file
    03-04-2015 /file/path/to/the/file
    

    or:

    /file/path/to/the/file 12-02-2015
    /file/path/to/the/file 12-02-2015
    /file/path/to/the/file 12-02-2015
    /file/path/to/the/file 12-02-2015
    
  • jayreed1
    jayreed1 over 4 years
    Just realized date +%D -r file or date +%F -r file would do nicely too.
  • jayreed1
    jayreed1 over 4 years
    Something like find . -exec grep -q set {} \; -exec echo -n "{} " \; -exec date +%F -r {} \;