Renaming multilple .txt files
6 views (last 30 days)
I have been trying to rename multiple text files with different methods I found around but could not make it work. My files are name as such:
So I have 13 depths and a triplicate for each depth. Which gives me 39 files. In the folder, thanks to my labeling, they are all correctly ordered in alphabetical order.
I would simply would like to rename those 39 files as:
Any help would be appreciated.
dpb on 31 Jul 2017
Edited: dpb on 31 Jul 2017
OK. To respond to the question raised...
Well, that's the hard way...use
d=dir('Z_X12_ABC*.txt'); % return all files matching wildcard
for i=1:length(d) % iterate over the list
data=importdata(d(i).name); % read file
% process that file here
% and move on to next.
A major advantage of the above is there is no "magic number" of 39 buried in the code and you can modify the search pattern to select particular subsets of interest depending on the needs at the time.
If you really do need multiple files at one time, then you can use cell array or other storage mechanism, but often it isn't needed.
Or, of course, while it's somewhat more difficult to write, once you do, there's no issue in generating the names dynamically--
fmt='Z_X12_ABC_%03dcm_1.txt'; % filename pattern
data=importdata(sprintf(fmt,i)); % open file
Same comments apply about whether need more than one at a time but has the "magic number" issue plus is much more to make other selections with.
Here's example of the above...
>> for i=1:3,disp(sprintf(fmt,i)),end
And, the extension to incorporate the last cyclic numeric field should be obvious in a nested loop structure if you're adamant about doing it that way instead of dir
More Answers (1)
Vipresh Gangwal on 28 Jul 2017
try using the dir function with an output argument.
myFiles = dir
% sort myFiles structure if you need to
for i = 1:length(myFiles)
% current file = myFile(i);
% rename current file
Make sure to ignore the folders "." and ".."