I can list the Python files in a directory from most recently updated to least recently updated with
ls -lt *.pyBut 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.
findfinds all*.pyfiles in current directory and prints modification time (epoch value) +:+ filename +NULbytesortcommand performs reverse numeric sort on first column that is timestampcutcommand removes 1st column (timestamp) from outputxargs -0 grepcommand searchespatternin each file
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 -ltri.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).