Linux – grep ouput filepath with file modified date

debiangreplinux

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

Best Answer

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.

Related Topic