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.

2 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
6

There is a very simple way if you want to get the filelist in chronologic order that hold the pattern:

grep -sil <searchpattern> <files-to-grep> | xargs ls -ltr 

i.e. you grep e.g. "hello world" in *.txt, with -sil you make the grep case insensitive (-i), suppress messages (-s) and just list files (-l); this you then pass on to ls (| xargs), sorting it by date (-t) showing date (-l) and all files (-a).

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.