rename files using matlab

Hello all,
I have a folder on my desktop that has 10 text files as following:
A.txt
Abgd.txt
B.txt
Bbgd.txt
C.txt
Cbgd.txt
S.txt
Sbgd.txt
std.txt
stdbgd.txt
I want to write a code that the changes the names of the first 8 files. I want to rename these files and add an underline (i.e. '_') after the first letterof each file. So my output should look like this:
A_.txt
A_bgd.txt
B_.txt
B_bgd.txt
C_.txt
C_bgd.txt
S_.txt
S_bgd.txt
Here is what I have done so far:
clear all; clc;
d = 'C:\Users\krraz\Desktop\Day13\*.txt';
oldnames = dir(d);
oldnames = {oldnames(~[oldnames.isdir]).name};
L = length(oldnames);
oldnames = oldnames(1:L-2);
points = oldnames(1:2:end);
points = cellfun(@(x) x(1:1), points, 'UniformOutput', false);
strr = '_.txt'; strr = string(strr);
for n = 1:numel(points)
formatSpec = '%1$s%2$s';
points{n} = sprintf(formatSpec,points{n},strr);
end
bgds = oldnames(2:2:end);
bgds = cellfun(@(x) x(1:1), bgds, 'UniformOutput', false);
strr = '_bgd.txt'; strr = string(strr);
for n = 1:numel(bgds)
formatSpec = '%1$s%2$s';
bgds{n} = sprintf(formatSpec,bgds{n},strr);
end
newnames = [points bgds];
newnames = sort(newnames);
for j=1:numel(oldnames)
movefile(d,newnames{j},'f');
end
But when I run my code, It generates a new folder on my desktop and doesn't change the names of the files. What am I doing wrong?
Any insight will be appreciated.

10 个评论

Hello, good day. I have a similar question. I just wanted to add the word 'cropped' at the end of my basefile name
my old file name:
BOX1 7CFU-GM D14 65 4x
BOX1 7CFU-GM D14 65 10x
BOX3 7CFU-PB D7 1 20x
BOX3 7CFU-PB D7 1 40x
BOX1 5CFU-GM D14 1 4x
BOX1 5CFU-GM D14 1 40x
the file name i wanted:
BOX1 7CFU-GM D14 65 4x cropped
BOX1 7CFU-GM D14 65 10x cropped
BOX3 7CFU-PB D7 1 20x cropped
BOX3 7CFU-PB D7 1 40x cropped
BOX1 5CFU-GM D14 1 4x cropped
BOX1 5CFU-GM D14 1 40x cropped
Thank you in advance.
%our dir() pulls in the names of all files, including those already cropped
%so we need to remove the 'cropped' ones from the list to process.
dinfo = dir('BOX*');
filenames = {dinfo.name};
is_it_cropped = contains(filenames, 'cropped');
filenames = filenames(~is_it_cropped);
nfiles = length(filenames);
for K = 1 : nfiles
thisfile = filenames{K};
[~, basename, ext] = fileparts(thisfile);
newname = [basename ' cropped' ext];
img = imread(thisfile);
newimg = imcrop(img, [50 50 600 600]); %use appropriate cropping here
imwrite(newimg, newname);
end
Tq very much sir/madam
Hello, I also have a question like this. In my file the files all have random names. I want to rename all the files as follow;
a0001, a0002... a0010, a0011... a0100, a0101... etc.
Any help would be much appreciated.
Thanks
The files that currently exist, what order are they to be renamed? Does 5CFU-GM.txt go before or after 05BHZ.D.2018.246.000000.txt ?
Are they to be renamed in the same directory? If so then it is a bit of a nuisance to deal with the issue that some of the existing files might already be named with the a* pattern. Or would it be okay to rename the existing a* pattern files first (effectively "compacting" to fill in any holes in the numbering sequence) before the others, so that if we just happen to get a10 before a0002 in the dir() results, that when we go to rename a10 to a0002, that we do not have to worry about the possibility that a0002 might already exist ? Or would it be acceptable to leave all existing a???? files untouched and find the highest number used for them and rename the other ones only after that?
... All of this worry about clashes is not a problem if we can create a new directory to rename the files into.
Currently they are named "a (1)" to "a (x)" for x number of files, as I just did a batch rename within the explorer window. However I get issues with ordering as Matlab likes to put "a (11)" before "a (2)" for example. So I just want to rename them all, and replace them in the same directory (or a new directory is fine too), with a0001 as the first name, with the number increasing. Thanks for your help,
ext = ".jpg"; %change to whatever is appropriate
for k = 1 : x
src = compose("a (%d)" + ext, k);
dst = compose("a%04d" + ext, k);
if exist(src, 'file');
movefile(src, dst);
else
fprintf('expected file "%s" not found\n', src);
end
end
Thank you very much!
Better would be
ext = ".jpg"; %change to whatever is appropriate
for k = 1 : x
src = compose("a (%d)", k) + ext;
dst = compose("a%04d", k) + ext;
if exist(src, 'file');
movefile(src, dst);
else
fprintf('expected file "%s" not found\n', src);
end
end
...just on the remote chance that the file extension in ext happens to contain a % that compose() would try to act on...
How to rename the data file using matlab

请先登录,再进行评论。

 采纳的回答

You have
d = 'C:\Users\krraz\Desktop\Day13\*.txt';
which includes the *.txt . You do not change d in your code. Later you have
movefile(d,newnames{j},'f');
but d still has the *.txt part, so it is going to move all the text files instead of moving one at a time.
projectdir = 'C:\Users\krraz\Desktop\Day13';
dinfo = dir( fullfile(projectdir, '*.txt') );
oldnames = {dinfo.name};
unwanted = cellfun(@isempty, regexp(oldnames, '^[A-Z][^_].*') );
oldnames(unwanted) = [];
newnames = regexprep(oldnames, '^(.)', '$1_');
for K = 1 : length(oldnames)
movefile( fullfile(projectdir, oldnames{K}), fullfile(projectdir, newnames{K}) );
end

6 个评论

hello,
I have a question about similiar subject
I have several files
LM.BARI..BHZ.D.2018.246.000000.txt
LM.BARI..BHZ.D.2018.247.000000.txt
LM.BARI..BHZ.D.2018.248.000000.txt
LM.TOGK..BHZ.D.2018.246.000000.txt
LM.TOGK..BHZ.D.2018.247.000000.txt
LM.TOGK..BHZ.D.2018.248.000000.txt
I would like to renama all those files as
BARI_Z_246.txt
BARI_Z_247.txt
BARI_Z_248.txt
TOGK_Z_246.txt
TOGK_Z_247.txt
TOGK_Z_248.txt
could you help me ?
thanks
newnames = regexprep(oldnames, '^\w+\.(\w+)\.\...(\w)\.\w\.\d{4}\.(\d{3}).*$', '$1_$2_$3.txt');
Dose this code replace all of the code in the original question, or dose it replace just a section of it?
How do I modify "regexprep(oldnames, '\w*', 'JOY_Y', 'once')" to only output "JOY_Y"? Currently it takes a file named "SigGen18_2022-05-26_07-45-21" and outputs "{'JOY_Y-05-26_07-45-21.mat'}"
Why? The output for that would be repmat({'JOY_Y'}, numel(oldnames), 1) except for fiddling for the case of empty entries.

请先登录,再进行评论。

更多回答(3 个)

KSSV
KSSV 2017-5-5
编辑:KSSV 2017-5-5
% Get all text files in the current folder
files = dir('*.txt');
% Loop through each file
for id = 1:length(files)
% Get the file name
[~, f,ext] = fileparts(files(id).name);
rename = strcat(f,'_',ext) ;
movefile(files(id).name, rename);
end
Run this code the folder which has your text files.

1 个评论

This code does NOT exactly do what I wanted. It adds _ to every file. I wanted to add _ after the first letter of the name of each file. But it helped, thank you KSSV!

请先登录,再进行评论。

Hello,
I Have a question about the same subject.
I have several files:
FoodS01HealthSession1.mat
FoodS01PracticeSession1.mat
FoodS01TasteSession1.mat
FoodS01TestSession1.mat
That go from S01 to S021 and I would like to all rename them as following
FoodSub110HealthSession1.mat
FoodSub110PracticeSession1.mat
FoodSub110TasteSession1.mat
FoodSub110TestSession1.mat
from 110 to 130
I cannot manage doing it using the function rename, as I donnnot know how to correctly code the loop nor using the function.
Could anyone help me?
Thanks a lot

1 个评论

Untested
projectdir = '.';
dinfo = dir( fullfile(projectdir, '*.txt') );
oldnames = {dinfo.name};
lookfor = 'FoodS0';
wanted = strncmp(oldnames, lookfor, length(lookfor));
oldnames(~wanted) = [];
for K = 1 : length(oldnames)
this_name = oldnames{K};
old_info = regexp(this_name, '(?<prefix>\D+)(?<id>\d+)(?<suffix>.+)', 'names';
old_id = str2double(old_info.id);
new_name = [old_info.prefix 'ub' sprintf('%03d', old_id+109) old_info.suffix];
movefile( fullfile(projectdir, this_name), fullfile(projectdir, new_name) );
end

请先登录,再进行评论。

Matteo
Matteo 2023-3-7

0 个投票

Good morning everyone, I should import a series of PDF doc named 'abstract_included-1.pdf' (from 1 to 225) and then perform a linguistic analysis (tokenization and lemmatization) on each doc. I would like to do this through a loop, but I can't give the right input to make the loop go through all the documents. Could anyone help me?

类别

帮助中心File Exchange 中查找有关 File Operations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by