Work through it one step at a time:
$ ls -lt *.txt
-rw-r--r-- 1 stew stew 18 Feb 5 19:53 file3.txt
-rw-r--r-- 1 stew stew 18 Feb 5 19:53 file2.txt
-rw-r--r-- 1 stew stew 18 Feb 5 19:53 file1.txt
We have three files, but you only wanted two. Let's tail
it:
$ ls -lt *.txt | tail -n 2
-rw-r--r-- 1 stew stew 18 Feb 5 19:53 file2.txt
-rw-r--r-- 1 stew stew 18 Feb 5 19:53 file1.txt
Ok, that's good but we really only want two filenames. ls -l
isn't the right tool, we can just use ls
:
$ ls -t *.txt | tail -n 2
file2.txt
file1.txt
Then put that output into cat
as arguments with $()
:
$ cat $(ls -t *.txt | tail -n 2)
content of file 2
content of file 1
You asked about how to use an alias for ls -lthr
. -l
doesn't really work well because it prints more than filenames. -h
only makes sense if -l
is there. So here's an example for ls -tr
:
$ alias lt='ls -tr'
$ cat $(lt *.txt | tail -n 2)
content of file 2
content of file 3
If you have something in your .bashrc
like alias ls='ls -lthr'
, then you can use command ls
or env ls
. If you want something else that handles odd characters (such as newlines) in files too, here's an example using find
instead:
cat $(find . -name '*.txt' | tail -n 2)
However ordering may not be the same as with your ls
solution and it will also search subdirectories.
ls
? – ewr3243 Feb 05 '21 at 18:51ls
– ewr3243 Feb 05 '21 at 19:00