Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash and sort files in order

Tags:

bash

sorting

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?

like image 248
Open the way Avatar asked Nov 17 '09 06:11

Open the way


People also ask

How do I sort files in bash?

Bash Sort Files Alphabetically By default, the ls command lists files in ascending order. To reverse the sorting order, pass the -r flag to the ls -l command, like this: ls -lr . Passing the -r flag to the ls -l command applies to other examples in this tutorial.

How do you sort in ascending order in bash?

Sort a File Numerically To sort a file containing numeric data, use the -n flag with the command. By default, sort will arrange the data in ascending order. If you want to sort in descending order, reverse the arrangement using the -r option along with the -n flag in the command.

How do I sort in descending order in bash?

2. -r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -r flag. the -r flag is an option of the sort command which sorts the input file in reverse order i.e. descending order by default.

How do I sort multiple files in Linux?

Another way to sort multiple files simultaneously is to pipe the find command output to sort and use the --files0-from= option in the sort command. Specify the -print0 option in find to end file name with the NUL character and ensure the program properly reads the file list.


2 Answers

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 '_'

like image 163
Puppe Avatar answered Sep 23 '22 04:09

Puppe


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_* 
like image 36
Pär Wieslander Avatar answered Sep 20 '22 04:09

Pär Wieslander