MareB
MareB

Reputation: 77

Matlab how to change file names from 1_x_10_a.jpg to 01_x_010_a.jpg

I have really a lot of files named like:

1_x_0_a.jpg, 1_x_0_b.jpg, 1_x_5_a.jpg ... 15_x_160_a.jpg, 15_x_160_b.jpg, 15_x_165_a.jpg

I would like to change the file names as follows:

01_x_000_a.jpg, 01_x_000_b.jpg, 01_x_005_a.jpg  

So, before x should be a number with 2 dig and after x with 3 digits.

Upvotes: 1

Views: 845

Answers (3)

Squazic
Squazic

Reputation: 3690

The following code should work on relatively newer versions of MATLAB.

fileStruct = dir;
files = {fileStruct.name};
for oldFile = files
    oldFile = oldFile{1};  //Takes string out of cell

    // Embedding the sprintf in a regexprep only works in certain versions
    newFile = regexprep(oldFile, '^(\d*)', '${sprintf(''%02d'', str2num($1))}');
    newFile = regexprep(newFile, '(?<=_)(\d*)(?=_)', '${sprintf(''%03d'', str2num($1))}');

    movefile(oldFile, newFile);
end

Upvotes: 2

erik
erik

Reputation: 2446

If you are on a Unix or Linux machine you can try this small shell script:

In a terminal go to the directory where you have your files.

You can first try it without really renaming your files, by replacing the mv with echo to see if it works as expected.

for file in *; do
  mv $file $(echo $file | awk -F '_' '{ printf "%02d_%s_%003d_%s\n", $1, $2, $3, $4 }')
done

or as a one liner

for file in *; do mv $file $(echo $file | awk -F '_' '{ printf "%02d_%s_%003d_%s\n", $1, $2, $3, $4 }'); done

For files

1_x_0_a.jpg
1_x_0_b.jpg
1_x_5_a.jpg
15_x_160_a.jpg
15_x_160_b.jpg
15_x_165_a.jpg

I get the result

01_x_000_a.jpg
01_x_000_b.jpg
01_x_005_a.jpg
15_x_160_a.jpg
15_x_160_b.jpg
15_x_165_a.jpg

Upvotes: 0

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Here are some steps that should help you:

  1. Use dir to get a list of file names.
  2. Use regexprep to replace starting numbers by starting numbers with leading zeros
  3. Use regexprep to replace middle numbers by starting numbers with up to two zeros
  4. Use rename to change the file names

Note that I have not tried it and the documentation of rename is a bit strange as it refers to ftp sites, but it might just work. If it does not work, I guess you can just copy all the files and then remove the old ones.

Upvotes: 0

Related Questions