Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grep files in date order

Tags:

bash

I can list the Python files in a directory from most recently updated to least recently updated with

ls -lt *.py

But how can I grep those files in that order?

I understand one should never try to parse the output of ls as that is a very dangerous thing to do.

like image 388
graffe Avatar asked Jan 01 '23 17:01

graffe


1 Answers

You may use this pipeline to achieve this with gnu utilities:

find . -maxdepth 1 -name '*.py' -printf '%T@:%p\0' |
sort -z -t : -rnk1 |
cut -z -d : -f2- |
xargs -0 grep 'pattern'

This will handle filenames with special characters such as space, newline, glob etc.

  1. find finds all *.py files in current directory and prints modification time (epoch value) + : + filename + NUL byte
  2. sort command performs reverse numeric sort on first column that is timestamp
  3. cut command removes 1st column (timestamp) from output
  4. xargs -0 grep command searches pattern in each file
like image 65
anubhava Avatar answered Jan 04 '23 06:01

anubhava