user3182395
user3182395

Reputation:

How to list files in linux shell using `ls` as they are listed in the corresponding folder

I have a problem. When I use only ls command in the shell my files are listed as following (weird):

[HorribleSubs] Fairy Tail - 166 [720p].mkv
[HorribleSubs] Fairy Tail - 16 [720p].mkv
[HorribleSubs] Fairy Tail - 167 [720p].mkv

When I open my folder though, the files are listed like this (preferred):

[HorribleSubs] Fairy Tail - 16 [720p].mkv
...
...
[HorribleSubs] Fairy Tail - 166 [720p].mkv
[HorribleSubs] Fairy Tail - 167 [720p].mkv

How can I use the ls command to list the files in the shell exactly as in the corresponding folder. In the folder it is ordered "By Name".

When I type ls -v the list is as following:

[HorribleSubs] Fairy Tail - 11 [720p].mkv
[HorribleSubs] Fairy Tail - 12 [720p].mkv
[HorribleSubs] Fairy Tail - 13 [720p].mkv
...
...
[HorribleSubs] Fairy Tail - 175 [720p].mkv
[Horriblesubs] Fairy Tail - 01  [720p].mkv
[Horriblesubs] Fairy Tail - 02 [720p].mkv
[Horriblesubs] Fairy Tail - 03 [720p].mkv
[Horriblesubs] Fairy Tail - 04 [720p].mkv
[Horriblesubs] Fairy Tail - 05 [720p].mkv
[Horriblesubs] Fairy Tail - 06 [720p].mkv
[Horriblesubs] Fairy Tail - 07 [720p].mkv
[Horriblesubs] Fairy Tail - 08 [720p].mkv
[Horriblesubs] Fairy Tail - 09 [720p].mkv
[Horriblesubs] Fairy Tail - 10 [720p].mkv

Upvotes: 0

Views: 1187

Answers (3)

smac89
smac89

Reputation: 43098

With the sort utility the user also has the option of specifying a starting column that is to be used for the sorting. So this command:

ls | sort -k 1.5n

Will sort using the 1st column and the starting at the 5th field. Assuming your files all start with the word file, this should use the number after that word to sort in natural order

Output:

file01.txt
file11.txt
file16.txt
file116.txt
file167.txt

For your new case (Fairy Tail - # [720p].mkv...), try this command:

ls | sort -k4n

Upvotes: 1

asf107
asf107

Reputation: 1146

you could always pipe the output of any command to the UNIX sort utility, and sort it however you'd like. For instance:

% ls | sort 
file16.txt
file166.txt
file167.txt

Upvotes: 0

yankee
yankee

Reputation: 40800

You can use ls -v for "natural sorting"

From the man page:

-v natural sort of (version) numbers within text

Upvotes: 1

Related Questions