Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grab the last result of a find command?

Tags:

bash

The result of my find command produces the following result

./alex20_0  
./alex20_1  
./alex20_2  
./alex20_3  

I saved this result as a variable. now the only part I really need is whatever the last part is or essentially the highest number or "latest version".

So from the above string all I need to extract is ./alex20_3 and save that as a variable. Is there a way to just extract whatever the last directory is outputted from the find command?

I would do the last nth characters command to extract it since its already in order, but it wouldn't be the same number of characters once we get to version ./alex20_10 etc.

like image 236
DDisciple Avatar asked Oct 16 '25 13:10

DDisciple


2 Answers

Try this:

your_find_command | tail -n 1

find can list your files in any order. To extract the latest version you have to sort the output of find. The safest way to do this is

find . -maxdepth 1 -name "string" -print0 | sort -zV | tail -zn1

If your implementation of sort or tail does not support -z and you are sure that the filenames are free of line-breaks you can also use

find . -maxdepth 1 -name "string" -print | sort -V | tail -n1
like image 26
Socowi Avatar answered Oct 18 '25 08:10

Socowi