Rename files named 1, 2, 3,…, 10, 11, … in folder

2019-07-10 00:15发布

问题:

I have a set of files in a folder and they are named as 1, 2 , 3, ..., 10, 11,... and I am running a MATLAB code on these files and it is taking the files as 1, 10, 11, 12,...(wrong order) which I don't want. I want to get the files in the sequence 1, 2, 3, ... only. So, is there a way to do this in MATLAB (I am using dir() command to get all the files of the folder)?

My MATLAB code goes as follows:

file_names= dir('DirContainingFiles1,2,3,...');
for imgj=1: length(file_names)
    file= file_names(imgj).name;
    ......
    ......
end

So, this file variable above is supposed to get all the files in each loop in a sequence 1, 2, 3,... But it is getting in 1, 10, 11,... sequence (text based scheme). Please help in getting it in numbered sequence.

回答1:

As you tagged this with shell, I assume you are happy to correct the issue in the shell. So, you could use rename (also known as Perl rename and prename) in the shell to zero pad all numbers out to say, 5 places:

rename --dry-run 's/\d+/sprintf("%05d",$&)/e' *

So, if I start with this:

-rw-r--r--   1 mark  staff    0 16 Jan 12:23 0
-rw-r--r--   1 mark  staff    0 16 Jan 12:23 1
-rw-r--r--   1 mark  staff    0 16 Jan 12:23 11
-rw-r--r--   1 mark  staff    0 16 Jan 12:23 2
-rw-r--r--   1 mark  staff    0 16 Jan 12:23 Freddy 73 Frog

I end up with this:

-rw-r--r--   1 mark  staff    0 16 Jan 12:23 00000
-rw-r--r--   1 mark  staff    0 16 Jan 12:23 00001
-rw-r--r--   1 mark  staff    0 16 Jan 12:23 00002
-rw-r--r--   1 mark  staff    0 16 Jan 12:23 00011
-rw-r--r--   1 mark  staff    0 16 Jan 12:23 Freddy 00073 Frog


回答2:

Here is a MATLAB solution:

cd DirContainingFiles1,2,3,...
names = strsplit(ls);
[~,idx]=sort(str2double(names));
for name = names(idx)
    disp(name{1})
    ....
end

You don't need to rename files. Get list of the files using ls. Convert them to numeric format and get index of the sorted elements.

If you want to use dir:

file_names= dir('DirContainingFiles1,2,3,...'); 
names = {file_names(3:end).name};
[~,idx]=sort(str2double(names));
for name = names(idx)
    disp(name{1})
    ....
end


回答3:

Just use

[natsortfiles][1](file_names);

before entering the loop, it sorts by numerical value while

sort(file_names); 

sorts by text based value.