Bash and sort files in order


Question

with a previous bash script I created a list of files:

data_1_box
data_2_box
...
data_10_box
...
data_99_box

the thing is that now I need to concatenate them, so I tried

ls -l data_*

but I get

.....
data_89_box
data_8_box
data_90_box
...
data_99_box
data_9_box

but I need to get in the sucession 1, 2, 3, 4, .. 9, ..., 89, 90, 91, ..., 99

Can it be done in bash?

1
30
11/17/2009 7:03:05 AM

Accepted Answer

ls data_* | sort -n -t _ -k 2

-n: sorts numerically
-t: field separator '_'
-k: sort on second field, in your case the numbers after the first '_'

61
11/17/2009 7:06:25 AM

How about using the -v flag to ls? The purpose of the flag is to sort files according to version number, but it works just as well here and eliminates the need to pipe the result to sort:

ls -lv data_*

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon