Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort list of files by date in bash

Given a text file containing some list of files, e.g.

$ cat file_list.txt
/var/x/file1.txt
/var/y/file2.txt
<etc>

How can I sort this list of files by some criteria - like their last accessed time, or last changed time?

Thanks in advance.

like image 242
DMCoding Avatar asked Mar 18 '23 02:03

DMCoding


2 Answers

You can use stat command with sort like this:

while read -r line; do
   stat -c '%Y %n' "$line"
done < file_list.txt | sort -n | cut -d ' ' -f2
  • stat -c '%Y %n' lists time of last modification, seconds since Epoch followed by a space and file name
  • sort -n sorts timestamps and their filename numerically
  • cut -d ' ' -f2 prints only file names from sort's output
like image 123
anubhava Avatar answered Mar 31 '23 10:03

anubhava


Try one liner (by modification time):

ls -t $(cat file_list.txt)

OR

ls -t `cat file_list.txt`
like image 39
SMA Avatar answered Mar 31 '23 10:03

SMA