LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Finding largest file number in the pattern (https://www.linuxquestions.org/questions/linux-newbie-8/finding-largest-file-number-in-the-pattern-4175472066/)

rpd25 08-04-2013 10:51 AM

Finding largest file number in the pattern
 
Hi,

I need a help in finding the largest file number in the file pattern.
As example, the largest file number is file.153.res in the following file list.

file.0.res
file.1.res
file.2.res
file.3.res
...
file.153.res

Please let me know what linux script would find the largest pattern.
Thanks in advance.

Warm regards,
Rakesh

Firerat 08-04-2013 11:31 AM

something like

Code:

ls /path/to/dir/ | sort -t. -k2,2 -rg | head -n1
# or long format
ls /path/to/dir/ | sort --field-separator=. --key=2,2 --reverse --general-numeric-sort | head --lines=1

so we get sort to 'split' the input into 3 fields, do a numerical sort on field 2, reversed so highest is first then using head to limit output to the "first" line

I'm sure there are other ways


if you have control over the filenames, you could pad with 0, then ls would do the sort for you, ls -r | head -n1


assuming a simple count..
1 2 3 .. 100 .. 200
Code:

for i in {1..200};do
  FileName=file.$(printf "%03d" $i).res
done

will give you file.001.res , file.002.res

the above is a little redundant, since for i in {001..200} will achieve the same without the need to mess with printf,
just demonstrates how printf can help

rpd25 08-04-2013 11:44 AM

Thank you for the quick reply.

The script works fine. However, I need to select the largest file number in "file.*.res" starting with the name "file".

druuna 08-04-2013 11:45 AM

If the number is the only dynamic part and no leading zero's are used:
Code:

ls -v file*res | tail -1
EDIT: You've asked this exact same question before: Finding max number in filename and opening it

rpd25 08-04-2013 12:12 PM

Sorry to bother. This is a very foolish question.

How to copy the file with largest number to other directory?
I tried using the following command but it didn't work
ls -v file*res | tail -1 | cp `ls` ../

druuna 08-04-2013 12:16 PM

Quote:

Originally Posted by rpd25 (Post 5002714)
Sorry to bother. This is a very foolish question.

How to copy the file with largest number to other directory?
I tried using the following command but it didn't work
ls -v file*res | tail -1 | cp `ls` ../

Code:

cp "$(ls -v file*res | tail -1)" /path/to/destination/

rpd25 08-04-2013 12:27 PM

Works Smoothly. Thanks.


All times are GMT -5. The time now is 02:01 PM.