Finding max number in filename and opening it

Hi,

I have files named as

energy.dat.1
energy.dat.2
energy.dat.3
...
energy.dat.2342

I would like to find the file with maximum number in the filename (ex. energy.dat.2342) and open it.

Would you please share your expertize in writing the script?

Thanks in advance.

ls energy.dat.*|sort -rn|head -1
1 Like

I tried the command. However it gave max file number as 99 (although the folder contains thousands of file)

$ls energy.dat.*|sort -rn|head -1
energy.dat.99

Is there any way to store the file name with maximum number in a variable?
I want to open this file for plotting in octave/gnuplot/python/scilab.

Thanks you.

Try this:

energy.dat.* | awk -F\. 'm<$NF{m=$NF;s=$0}END{print s}'
1 Like

if you want it to store in a variable , just use the below command:

max_number=`ls energy.dat.*|sort -rn|head -1`
1 Like

A slight modification to vbe's one-liner:

ls energy.dat.* | sort -nrk1.12 | head -1
1 Like

Hi,
Could you please explain how that command behaved without key -k specification .
I don't have unix to test it currently

Thanks

1 Like

Thank you very much for your help.
I am able to get the max number in the file name.

ls energy*| sort -t"." -n +2 | tail -1