Alexandre Santos
Alexandre Santos

Reputation: 8338

sorting file names ascending where names have a dash in bash

I have a list of files in a folder.

The names are:

1-a
100-a
2-b
20-b
3-x

and I want to sort them like

1-a
2-b
3-x
20-b
100-a

The files are always a number, followed by a dash, followed by anything.

I tried a ls with a col and sort and it works, but I wanted to know if there's a simpler solution.

Forgot to mention: This is bash running on a Mac OS X.

Upvotes: 0

Views: 1661

Answers (2)

Dimitre Radoulov
Dimitre Radoulov

Reputation: 28000

Some ls implementations, GNU coreutils' ls is one of them, support the -v (natural sort of (version) numbers within text) option:

% ls -v
1-a  2-b  3-x  20-b  100-a

or:

% ls -v1
1-a
2-b
3-x
20-b
100-a

Upvotes: 2

chepner
chepner

Reputation: 531265

Use sort to define the fields.

sort -s -t- -k1,1n -k2 filenames.txt

The -t tells sort to treat - as the field separator in input items. -k1,1n instructs sort to first sort on the first field numerically; -k2 sorts using the remaining fields as the second key in cade the first fields are equal. -s keeps the sort stable (although you could omit it since the entire input string is being used in one field or another).

(Note: I'm assuming the file names do not contain newlines, so that something like ls > filenames.txt is guaranteed to produce a file with one name per line. You could also use ls | sort ... in that case.)

Upvotes: 1

Related Questions