user1551817
user1551817

Reputation: 7451

How to change the order in which files are listed by bash

I have some files. When I list them I get the order:

frame0001i0002.png
frame0001.png
frame0002i0003.png
frame0002.png
frame0003i0004.png
frame0003.png
frame0004.png
frame0005.png
frame0006.png

I had assumed that frame0001.png would come before frame0001i0002.png, because I need to operate on them in the order:

frame0001.png
frame0001i0002.png
frame0002.png
frame0002i0003.png
frame0003.png
frame0003i0004.png
frame0004.png
frame0005.png
frame0006.png

Do I need to rename them to appear in the order that I want?


Ultimately I want to change their names to:

frame0001.png
frame0002.png
frame0003.png
frame0004.png
frame0005.png
frame0006.png
frame0007.png
frame0008.png
frame0009.png

and in the order from the cell above.

Upvotes: 1

Views: 498

Answers (2)

Ivan
Ivan

Reputation: 7277

ls can also do this with -v option

$ ls -vw1 *png
frame0001.png
frame0001i0002.png
frame0002.png
frame0002i0003.png
frame0003.png
frame0003i0004.png
frame0004.png
frame0005.png
frame0006.png

From ls help

$ ls --help
...
  -v                         natural sort of (version) numbers within text
  -w, --width=COLS           set output width to COLS.  0 means no limit
...

Upvotes: 1

Aaron
Aaron

Reputation: 24812

You encounter this problem because i comes before . in your default sort order.

Using the following you can get the expected order :

sort -t'.' -k 1,1

This defines . is a field separator and that we should only consider the first field (the part before the extention) for the sort order. We're now comparing frame0001 with frame0001i0002, and the shortest will be printed first.

Upvotes: 2

Related Questions