How to remove first few characters from multiple file names?

3 views (last 30 days)
I have multiple files with similar first few characters stored in a folder. How would I remove the first few letters from multiple files so that I am only left with characters that follow the first few letters?
For example: Original - "Mark_Mathworks_3088" change to "Mathworks_3088"? In the example I want to remove "Mark_", I have few files with "Mark" in the front and others with different names such as - "Nat", "Watt", & "Rick" which I want to remove as well.
What would be a correct code to make this work?

Answers (1)

Image Analyst
Image Analyst on 11 Jan 2018
Get the string first from your structure or cell array.
filename = dirListing.name; % if you got by using dir() function or
filename = cellArray{index}; % if it's in a cell array.
Then find the underline and get from there on:
underlineLocation = strfind(filename, '_');
filename = filename(underlineLocation + 1 : end);
  5 Comments
Image Analyst
Image Analyst on 12 Jan 2018
Edited: Image Analyst on 12 Jan 2018
So, simply change the .m to .docx, .pdf, .*, or whatever in the file pattern in the call to dir(). It doesn't matter to the rest of code.
Kaitlynn Conway
Kaitlynn Conway on 25 Jan 2019
I tried using this code to shorten the name of my files. I just wanted to keep the first 21 letters of the file name and save the new files in a new folder.
It did all of that correctly, except when I ran the program, the files it saved in the new folder werent tifs anymore. How do I rename my files without making sure the content of the files remain unchanged?
clc
clear variables
close all
inputFolder = ('D:\Hytrel Testing\Hytrel EL217-5-2'); % Wherever you want.
outputFolder = ('D:\Hytrel Testing\Hytrel EL217-5-2\Renamed_Files'); % Wherever you want. Can be the same as inputFolder if you want.
dirListing = dir(fullfile(inputFolder, '*.tif'));
for k = 1 : length(dirListing)
baseFileName = dirListing(k).name;
%underlineLocation = strfind(baseFileName, '_');
if ~isempty(baseFileName)
outputBaseFileName = baseFileName(1 : 21);
inputFileName = fullfile(inputFolder, baseFileName);
outputFileName = fullfile(outputFolder, outputBaseFileName);
fprintf('Ranaming %s to %s.\n', baseFileName, outputFileName);
if isequal(inputFolder, outputFolder)
% Rename in place.
movefile(inputFileName, outputFileName);
else
% Make copy in other folder.
copyfile(inputFileName, outputFileName);
end
end
end

Sign in to comment.

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!