Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List newest file, by type (.txt), after searching recursively, in a terminal

I'm trying to get my terminal to return the latest .txt file, with path intact. I've been researching ls, grep, find, and tail, using the '|' functionality of passing results from one utility to the next. The end result would be to have a working path + result that I could pass my text editor.

I've been getting close with tests like this: find . | grep '.txt$' | tail -1

..but I haven't had luck with grep returning the newest file - is there a flag I'm missing?

Trying to use find & ls isn't exactly working either:

find . -name "*.txt" | ls -lrth

..the ls returns the current directories instead of the results of my find query.

Please help!

like image 393
i4n Avatar asked Jan 27 '26 12:01

i4n


2 Answers

You're so very close.

vi "$(find . -name '*.txt' -exec ls -t {} + | head -1)"
like image 102
Chris Jester-Young Avatar answered Jan 30 '26 02:01

Chris Jester-Young


find /usr/share -name '*.txt' -printf '%C+ %p\n' | sort -r | head -1 | sed 's/^[^ ]* //'
like image 41
Seth Robertson Avatar answered Jan 30 '26 02:01

Seth Robertson