Renaming files using MATLAB

308 views (last 30 days)
How can I rename files on my computer using MATLAB?
I have many files on my computer and want to use MATLAB to rename them all at once.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 28 Jul 2020
From MATLAB, you can use the "movefile" function to rename files on your machine:
For more information on managing files and folders in MATLAB see this documentation:
Alternatively, you can use the "system" command which executes on the local operating system.
On Windows using CMD, the "rename" command works like this:
C:> rename file_path new_name
C:> rename C:\Temp\file1.txt file2.txt
So in MATLAB, from the directory with the file you could execute:
>> system("rename " + "old_name.txt" + " " + "new_name.txt")
If the file names contain spaces, this can confuse the operating system, so a more robust approach is to wrap each file name in double quotes like this:
>> system("rename " + '"' + "old name.txt" + '" "' + "new name.txt" + '"')
This produces a system command like this:
C:> rename "old name.txt" "new name.txt"
To use MATLAB variables for the old and new file names you can use these MATLAB commands:
>> old_path_to_file = "C:\Temp\test a.txt";
>> new_filename = "test b.txt";
>> cmd = "rename " + '"' + old_path_to_file + '" "' + new_filename + '"';
>> system(cmd);
On a Linux or macOS (Unix) system, this would be:
>> old_path_to_file = "/tmp/test a.txt";
>> new_filename = "test b.txt";
>> cmd = "mv " + '"' + old_path_to_file + '" "' + new_filename + '"';
>> system(cmd);

More Answers (0)

Categories

Find more on Software Development Tools in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!