简体   繁体   中英

Sort files by number at end in bash/perl

I'm trying to sort a huge list of files into the following format:

file-55_357-0.csv
file-55_357-1.csv
file-55_357-2.csv 
file-55_357-3.csv 
...

Is there a simple way to do this in bash or perl? In other words, is there a way to write the perl script such that it goes through all of them in numerical order? For instance, when I create my @files , can I make sure the script goes through them all in this sorting -- how could I create a my @sorted array? I ask because I want to append all these files together vertically, and they need to be in the sorted order. Thanks so much!

You can use the sort command, which is neither part of bash nor part of perl.

With input data in input.txt :

file-55_357-123.csv
file-55_357-0.csv
file-55_357-21.csv 
file-55_357-3.csv 

From my shell, (any shell, not just bash) I can do the following:

$ sort -t- -nk3 input.txt
file-55_357-0.csv
file-55_357-3.csv
file-55_357-21.csv
file-55_357-123.csv

The -t option specifies a delimiter, -n says to compare numeric values (so that 21 comes after 3 rather than before) and -k 3 says to sort on the third field (per the delimiter).

use Sort::Key::Natural qw( natsort );

my @sorted = natsort @file_names;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM