Matlab: how to rename bulk files if varying length - matlab

I am trying to rename over a thousand files of varying length. For example, my original file names are:
1-1.txt
1-13.txt
12-256.txt
...
I would like these files to appear as follows:
100000-1-1.txt
100000-1-13.txt
100000-12-256.txt
...
I have been trying to use the following script:
d = 'directoryname';
names = dir(d);
names = {names(~[names.isdir]).name};
len = cellfun('length',names);
mLen = max(len);
idx = len < mLen;
len = len(idx);
names = names(idx);
for n = 1:numel(names)
oldname = [d names{n}];
newname = sprintf('%s%100000-*s',d,mLen, names{n});
dos(['rename','oldname', 'newname']); % (1)
end
What am I doing wrong? Thanks in advance for your help!!

See if this works for you -
add_string = '100000-'; %//'# string to be concatenated to all filenames
pattern = fullfile(d,'*.txt') %// we are renaming only .txt files
files_info = dir(pattern)
org_paths = fullfile(d,{files_info.name})
new_paths = fullfile(d,strcat(add_string,{files_info.name}))
if ~isempty(org_paths{1}) %// Make sure we are processing something
cellfun(#(x1,x2) movefile(x1,x2), org_paths, new_paths); %// rename files
end
Edit
add_string = '100000-'; %//'# string to be concatenated to all files
pattern = fullfile(d,'*.txt') %// Rename .txt files
files_info = dir(pattern);
f1 = {files_info.name};
org_paths = cellfun(#(S) fullfile(d,S), f1, 'Uniform', 0);
f2 = strcat(add_string,f1);
new_paths = cellfun(#(S) fullfile(d,S), f2, 'Uniform', 0);
if numel(org_paths)>0
if ~isempty(org_paths{1}) %// Make sure we are processing something
cellfun(#(x1,x2) movefile(x1,x2), org_paths, new_paths); %// rename all files
end
end

I don't really get what you are doing with len and mLen, but assuming that's correct, you just need the following changes within the for loop:
for n = 1:numel(names)
oldname = [d filesep names{n}]; %// include filesep to build full filename
newname = sprintf('100000-%s', names{n}); %// prepend '100000-' to names{n}
%// or replace by the simpler: newname = ['100000-' names{n}];
dos(['rename' oldname ' ' newname]); % (1) %// oldname and newname are variables
end

Related

Reading multiple text files with two columns in MATLAB

I want to read multiple text files. Each text file has two columns. All the two columns of all text files have same rows. I want to know, in MATLAB, how to read each text file then read each column one by one, subtract one column data from the other column and then read the next file and so on. I have written the following code but I am missing some step in the code. I appreciate your support. Thank you all.
for k = 1:9
filename = sprintf('Data_F_Ind000%d.txt',k);
a(:,k) = load(filename);
x = a(:,1)};
y = a(:,2);
z = x - y;
end
data = cell(9,1) ;
diff_data = cell(9,1) ;
for k = 1:9
filename = sprintf('Data_F_Ind000%d.txt',k);
a = load(filename);
data{i} = a ;
x = a(:,1)};
y = a(:,2);
diff_data{i} = x - y;
end
You can do this multiple ways. I imagine that you want to do something with z instead of just throwing it away every time. I would do this by taking advantage of an access pattern.
numFiles = 9;
numRows = ....; % not required but used to preallocate the a matrix
pattern = 1:2:numFiles * 2; % create a vector of 1 3 5 ...
a = zeros(numRows, numFiles * 2);
z = zeros(numRows, numFiles);
for k = 1:numFiles
fileName = sprintf('Data_F_Ind000%d.txt, 'k');
a(:,pattern(k):pattern(k) + 1) = load(fileName);
z(:,k) = a(:,pattern(k)) - a(:,pattern(k) + 1);
end
This is untested and is clearly missing some data but the intent should be clear. You don't need to preallocate variables but it helps speed calculations so I try to do it whenever possible.

Finding common words in multiple text files and saving them to new text file

If i had 10-20 text files and each file contains at-least 4-5 words which are common in all, how to get those words and to save them to a new text file.
I have tried many things, as my text files are coming one by one, so I cannot count the number of text files. Is there any way to save the text separately into different cell arrays without using a loop and then find common words.
Here is the code--
sdirectory = 'C:\Users\anurag\Desktop\Animals\Annotations\';
textfiles = dir([sdirectory '*.eng']);
sdirectory1 = 'C:\Users\anurag\Desktop\Animals\Images\';
imgfiles = dir([sdirectory1 '*.jpg']);
num_of_files = length(textfiles);
C = cell(num_of_files,1);
for w = 1:length(textfiles)
file = [sdirectory textfiles(w).name];
STR = importdata(file);
BL = cellfun(#lower,STR,'uni',0);
B = regexprep(BL,'<.*?>','');
B(strcmp(B, '')) = [];
tmp = regexp(B, '/| ', 'split');
C{w} = [tmp{:}];
end
where = [];
for j = 1:length(C)
file1 = [sdirectory1 imgfiles(j).name];
file2 = [sdirectory textfiles(j).name];
if find(strcmp(C{j},'alligator'))
where = [where num2str(j) '.eng, '];
disp(file2);
end
end
The file2 variable will show the path of matching text file to text alligator. But it will not store the path, but will overwrite the path as the new loop begins. So how to store each path separately so to access store data in text files separately and find common words in them.
You should first read in the files you are working with and store the words as cell arrays containing strings. Then you should compare the cell arrays in pairs and compare the results in pairs and son on until you have a single cell array.
If you have four files and (A, B, C, D) are four cell arrays of words from the files, you should compare A and B (result is AB), C and D (result is CD), then you should compare AB and CD to get the final cell array of words that are in all four files.
An example
basedir = '';
files = dir([basedir '*.eng']);
filenames = strcat({basedir}, {files.name});
Now filenames will hold the path to all the files you want to work on. You should then write a function that given a path opens the file and creates a cell array of words in the file, lets call this function read_my_data.
wordlists = {};
for i = 1:numel(filenames)
wordlists{i} = read_my_data(filenames{i});
end
If you have two cell arrays of strings A and B then you can find duplicates by sorting them both and then iterate over the arrays.
function C = duplicates(A,B)
i = 1; j = 1; k = 1;
C = {};
A = sort(A);
B = sort(B);
while i <= numel(A) & j <= numel(B)
switch strcmp(A{i}, B{i})
case -1
i = i + 1;
case 0
C{k} = A{i};
i = i + 1;
j = j + 1;
k = k + 1;
case 1
j = j + 1;
end
end
You can then loop over wordlists and find duplicates
while numel(wordlists) > 1
j = 1
tmp = {};
for i = 1:2:numel(wordlists)-1
tmp{j} = duplicates(wordlists{i}, wordslists{i+1});
j = j + 1;
end
wordlists = tmp;
end
Note that you need to make sure that numel(wordlists) is even or 1.

saving outputs from a loop in Matlab in different folders

I am using the codes below which save the output images in the same directory as is the m-file. I am trying to automate to save the output images in different folders with the folder name same as the 'file' name.
clear all;
files = dir('*.dat');
for k = 1:length(files);
filename = files(k).name;
data1 = fopen(filename,'r');
data2 = textscan(data1, '%f%f','headerlines',1,'CollectOutput',1);
data = data2{:,1};
x = data(:,1);
y = data(:,2);
plot(x, y);
[pathstr, name, ext] = fileparts(filename);
temp = ['fig', num2str(k), '.eps'];
print(gcf, '-depsc', temp);
fclose(data1);
end
Any help will be very much appreciated.
You have to create a subfolder (named after your filename), then print in this folder.
folderName = filename;
mkdir(folderName);
print( gcf , [folderName '/' filename] ); %or use `filesep` function to replace /

Creat a loop to generate a a mean value of data which I got form TXT files?

I trying to do script to evalute my lab data into matlab, I have lots of txt files for many samples, each sample has 30 txt files. I did a function to get the data from these files and store them into a structure that contains data and labels.
I would like to know if it is possible to load all the 30 files using loop instead of line by line .
function s = try1(fn)
% adapt for other file format according to your needs
fid = fopen(fn);
s.data = [];
% skip first lines
for k=1:6
l = fgetl(fid);
% read header
a = regexp(l,',','split');
s.labels = a;
l = fgetl(fid);
k=0;
end
while( (l~=-1)&(k<130) )
l = l(1:end-1);
a = regexp(l,', ','split');
a = regexpre
p(a, ',','.');
s.data = [s.data; str2double(a(2:4))];
l = fgetl(fid);
k = k+1;
end
fclose(fid);
end
To do what you want with a data directory and processing each file in a loop you can use a combination of fullfile(...) and a loop. This will likely work:
dataDirectory = 'c:/myDirectory';
allFilesDir = dir(fullfile(dataDirectory , '*.txt'));
allFN = {allFilesDir.name}
% Or do this:
% allFN = {'file1.txt', 'file2.txt'};
result = [];
for ind = 1:length(allFN)
myFN = fullfile(dataDirectory, allFN{ind});
result(ind) = try1(myFN);
end
% Now get the mean:
myMean = mean([result.data])

using a creation date of files and adding it to the name of the files in matlab

I have a lot of files which I want to edit all the names by including the creation date of files.
This what I have so far, but it does not work:
a='c:\test_for_namn_andring\*.*';
file_info=dir('c:\test_for_namn_andring\*.*');
names={file_info.name};
dates={file_info.date};
for i=3:length(names)
oldfilename = names;
newfilename = (strcat(names(1,3:end), dates(1,3:end)));
newfilename = fullfile(a, newfilename);
movefile(fullfile(a,oldfilename{i}),newfilename);
end
I did something similar in the past. Here is the code, adjusted to your needs
% define params
folder = 'd:/test';
name_filter = '*.*'; % any filter, e.g. '*.txt'
date_format = '_yyyymmddHHMMSSFFF'; % define the desired date string format
% process
f = dir(fullfile(folder, name_filter));
f([f.isdir]) = [];
names = {f.name}';
fullnames_old = cellfun(#(x) fullfile(folder, x), names, 'UniformOutput', false);
dates = cellstr(datestr([f.datenum]', date_format));
[pathstr, name, ext] = cellfun(#(x) fileparts(x), names, 'UniformOutput', false);
fullnames_new = cellfun(#(x, d, e) fullfile(folder, [x, d, e]), name, dates, ext, 'UniformOutput', false);
status = cellfun(#(x, y) movefile(x, y, 'f'), fullnames_old, fullnames_new);
assert(all(status), 'failed!'); % check result
Something like this should work:
file_info = dir(a);
for ii = 1:length( file_info )
if ~ file_info(ii).isdir
oldName = fullfile( a, file_info(ii).name );
newName = fullfile( a, sprintf( '%s_%s', file_info(ii).name, file_info(ii).date ) );
movefile( oldName, newName );
end
end
You should probably also check the return from movefile to handle errors. See the doc for more.