How to truncate/modify a file name

14 views (last 30 days)
Hi everyone,
The question pertains to modifying file names during a batch processing operation. Basically, I would like to truncate a certain portion of the file name and use that as the output name of the processed file. Please see the code below and the comments, outlining the question:
clc
clear all
files = dir('*.JPG');
filePrefix_cr = 'Cropped ';
% For example, let's use a file name like: S-0281 AB196C3 View 3.jpg.
% What I would like to have for a file name is: Cropped AB196C3 View 3.jpg.
% The result from this code is: Cropped S-0281 AB196C3 View 3.jpg.
% How do I truncate the S-0281, i.e. the first 6 characters of the file
% name, prior to introducing 'Cropped'?
for k = 1:numel(files)
rgb = imread(files(k).name);
% Runs a file modification process, e.g. a cropping process.
imwrite(rgb, [filePrefix_cr files(k).name]);
end
Thanks in advance for all the help and have a good week.
Regards

Accepted Answer

Walter Roberson
Walter Roberson on 13 Feb 2012
imwrite(rgb, [filePrefix_cr files(k).name(7:end)]);

More Answers (2)

Jeff E
Jeff E on 13 Feb 2012
This will truncate the first six chars. If the file name part you want to truncate changes in size, check out regexp to find, say, the first space in your string.
tname = 'S-0281 AB196C3 View 3.jpg':
tname2 = tname(7:end);

Sid
Sid on 13 Feb 2012
Thank you both for your answers!

Community Treasure Hunt

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

Start Hunting!