With GNU tools:
grep -H something * | awk -F: '{"date -r \""$1"\" +\"%F %R\"" | getline d; print d,$0}' | sort -n
Or,
ack something | awk -F: '{"date -r \""$1"\" +\"%F %R\"" | getline d; print d,$0}' | sort -n
This uses awk
to separate out the file name from the usual grep
output and awk
calls date
to retrieve the files date. grep
is given the -H
option to assure that a filename is shown on output even if only one appears on the command line.
As an example of the output:
$ grep setupcon /etc/init.d/* | awk -F: '{"date -r \""$1"\" +\"%F %R\"" | getline d; print d,$0}' | sort -n
2011-12-05 12:05 /etc/init.d/keymap.sh:# If setupcon is present, then we've been superseded by console-setup.
2011-12-05 12:05 /etc/init.d/keymap.sh:if type setupcon >/dev/null 2>&1; then
2011-12-08 18:00 /etc/init.d/console-setup: if setupcon --save; then
2011-12-08 18:00 /etc/init.d/console-setup:test -f /bin/setupcon || exit 0
2012-04-28 02:41 /etc/init.d/kbd:if which setupcon >/dev/null
2012-09-30 18:02 /etc/init.d/keyboard-setup: if setupcon -k 2>/dev/null; then
2012-09-30 18:02 /etc/init.d/keyboard-setup:test -f /bin/setupcon || exit 0
Explanation of awk
commands
-F:
This sets the field separator to :
so that the first field is the file name. (We have to hope that the file name itself does not contain a colon.)
"date -r \""$1"\" +\"%F %R\"" | getline d
This runs date -r filename +"%F %R"
to get the file's modification date in a form suitable for sorting. The date is stored in the variable d
.
print d,$0
This prints the data followed by the line of output from grep
.
tmp
or similar could help. That may not work for every environment, but I guess it could prevent that problem.