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?
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.
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.
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.
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.
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 '_'
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_*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With