I have some 100+ conf files that I am working. I need to find and replace various variable for all these files. For example, I'd like to find the line
Amplitude = 100; and replace it to: Amplitude = 200; for all files.
I've searched in online and found the solution only for one file. I'm looking for a way to do that in Matlab. Any ideas?
If these files can be opened as normal text files then I wouldn't use matlab. Notepad++ has an replace option for as many files as you want, just make sure, you test it out on a backup file first. so have it find "Amplitude = 100" and replace that by what you want.
To see how to do it, look here:
how-to-find-and-replace-lines-in-multiple-files
If you can't do that, put all the files in the same directory (you have to do this anyway). Then load the files in matlab with that directory and run a for loop. However it might be a bit slow./
Basically if you can do 1 file, you could do all of them with a for loop.
If you need help with that I show can some code I used before.
Well, Matlab solution would be to (recursively) open all files in the directory. Here I show example for non-recursive solution (it does not check subfolders), though it would be easy enough to modify it to search subfolders too if needed:
d = dir(yourPath);
for i = 1 : length(d)
if ~(d(i).isdir)
%d(i) is file.
replaceSingleFile(strcat(d(i).folder, d(i).name));
end
end
As you say, you already know how to do replace for a single file, though to have complete answer here, solution could be along the lines (in the function replaceSingleFile).
F = fopen(fileYouWantReplaced);
i = 1;
while (~feof(F))
L = fgetl(F);
L = strrep(L, 'Amplitude = 100;', 'Amplitude = 200;');
Buf{i} = L;
i = i + 1;
end
fclose(F);
%now just write all Buf to the same file again.
F = fopen(file..., 'w'); % Discard contents.
for i = 1 : numel(Buf)
fprintf(F, '%s\n', Buf{i});
end
fclose(F);
Related
In the below code I am trying to sort files based on a string within the name. I've been piecing this together with google searches and community help (I'm very new at matlab). Right now I'm getting two odd errors. First, when I try and make a folder, it creates some file (highlighted filein picture that I can't open and the wav files that should have been moved to the folder disappear.
I'm also having an issue where the code renames the first two data files moved to "01" and "01 (1)" and I have no idea why.
DirIn = 'C:\Folder\Experiment' %set incoming directory
eval(['filelist=dir(''' DirIn '/*.wav'')']) %get file list
for i = 1:length(filelist);
Filename = filelist(i).name
name = strsplit(Filename, '_');
newStr = extractBetween(name,7,8);
if strcmp(newStr,'01')
DirOut = fullfile(DirIn, '01');
mkdir DirIn DirOut
movefile(fullfile(filelist(i).folder, filelist(i).name), DirOut);
end
end
This should work:
DirIn = 'C:\Folder\Experiment'; %set incoming directory
filelist=dir(fullfile(DirIn, '*.wav')); %get file list
DirOut = fullfile(DirIn, '01');
for i = 1:length(filelist);
Filename = filelist(i).name
newStr = Filename(7:8);
if strcmp(newStr,'01')
if ~exist(DirOut)
mkdir(DirOut)
end
movefile(fullfile(filelist(i).folder, filelist(i).name), DirOut);
end
end
Firstly, you don't need eval to get the file list. eval impact performance significantly. The below is what you should have done:
filelist=dir(fullfile(DirIn, '*.wav'));
You don't need strsplit or extractBetween since you only intend to extract a part of the string by indexing, i.e. the 7th and 8th characters, you may do this:
newStr = Filename(7:8);
To use variable as an input, you need to use mkdir as a function rather than console command:
mkdir(DirOut)
Lastly, a bit of optimisation. Since DirOut is constant, you can take it outside the loop. You may also want to check if DirOut has already been created to avoid the warning message and overhead in mkdir.
There is no issue with movefile.
Couple things go wrong, first, it is not recommended to use eval. In this case you can just create a character array to pass to dir as follows:
filelist = dir([DirIn '/*.wav'])
Then, you have a strplit that appears to do nothing, since it looks like your files don't have '_' in them, so name will just return Filename. But that is not the issue, since you are using extractBetween on the Filename.
The following does not what you think it does,
mkdir DirIn DirOut
will create two directories named DirIn and DirOut in the current working directory of Matlab. To create the directories you want, use:
mkdir(DirOut)
Since the output directory did not exist before, I suspect Matlab moved the file to the input directory, and renamed it to 01, if you manually add the extension .wav it should be one of the original files.
Using the command
checkcode('function.m')
you can run the code analyzer on an m-file and output the report in the command window.
Is there any way to do this for TODO/FIXME reports? (without having to cd to the folder that contains the function and manually run it on the whole directory)
Bonus: If so, is it also possible to create custom tags? In eclipse, you can create custom TODO tags like "MTODO" and "JTODO" for different purposes/different people and have them displayed separately. Is this possible in Matlab?
Thanks in advance for any help! I will be continuing my google searches and will post the results if I find something.
You can use the internal function dofixrpt. This returns the HTML displayed in the report, rather than displaying the information at the command line, however.
% Run the report and show it
cd('myfolder')
dofixrpt;
% Alternatively, get the HTML of the report directly
html = dofixrpt;
% Write the HTML to a file
filename = tempname;
fid = fopen(filename, 'w');
fprintf(fid, '%s', html);
fclose(fid);
% View the HTML file
web(filename)
Type which dofixrpt or edit dofixrpt to see more details about what it does (it's basically a regular expression search for %.*TODO and %.*FIXME).
In the HTML report, you can find markers other than TODO and FIXME by specifying a custom marker (the default is NOTE). Unfortunately you can specify only one. If you're up to looking within dofixrpt and modifying it very slightly though, it would be very easy to make it look for more.
Finally you could also put in an enhancement request with MathWorks to provide a command similar to checkcode that will just do this for you and return the results at the command line. It seems like that would be very easy for them to do, and I'm surprised they haven't already done it, given that they've done something similar for helprpt, coveragerpt, deprpt etc.
Hope that helps!
I ended up writing my own code checker that calls checkcode on every m file in the specified folders.
fld_list = {pwd, 'folder', 'other_folder'};
nProblems = 0;
for iFld = 1:length(fld_list)
% fprintf('Checking %s...\n', fld_list{n});
files = dir(fullfile(fld_list{iFld}, '*.m'));
for f = 1:length(files)
filename = fullfile(fld_list{iFld}, files(f).name);
customCodeCheck(filename); %custom function
% check code analyzer
codeWarnings = checkcode(filename);
if not(isempty(codeWarnings))
fprintf('Problem found in %s\n', files(f).name);
for iData = 1:length(codeWarnings)
nProblems = nProblems + 1;
% print out link to problem
fprintf('line %d: %s\n', ...
filename, ...
codeWarnings(iData).line, codeWarnings(iData).line, ...
codeWarnings(iData).message);
end
end
end
end
You can add to this a customCodeCheck function that searches for TODO and FIXME and alerts you to their existence
function customCodeCheck(filename)
fileContents = fileread(filename);
toDos = strfind(fileContents, 'TODO');
fixMes = strfind(fileContents, 'FIXME');
% do other stuff
end
I am using MATLAB
I Have 51 files in their own directory all of .out extention created by a seperate program, all numbered 0 to 50.
ie
0.out
1.out
2.out
and so on til 50.out.
I need to load each file 1 by one to do calculations upon them within a for loop. How would I do this using the count variable to load the file, if the directory is set beforehand?
i.e.
%set directiory
cd(......)
%for loop
For count = 0:50,
data = count.out *<-----this line*
.....
Many thanks!
First generate the file name with
fileName = [int2str(count) '.out'];
then open the file with
fid = fopen(fileName, 'r');
The loading phase depends on the kind of file you want to read. Assuming it is a text file you can, for example, read it line after line with
while ~feof(fid)
line = fgetl(fid);
end
or use more specialized functions (see http://www.mathworks.it/it/help/matlab/text-files.html). Before the end of the for loop you'll have to close the file by calling
fclose(fid);
Another quite nice way to do it is to use the dir function
http://www.mathworks.co.uk/help/matlab/ref/dir.html
a = dir('c:\docs*.out')
Will give you a structure containing all the info about the *.out files in the directory you point it to, (or the path). You can then loop through it bit by bit. using fopen or csvread or whatever file reading function you want to use.
I have a data set of big number of videos so, I want to read these videos and save each video separately with its name because it consumes a lot of time to process among all these videos every time specially for training and classification. If you have any idea how can read all video files in the specified folder D:\words of format .avi and save each one with its own name as .MAT file.
But this code doesn't work
Thanks,,,
files = fuf('D:\words');
for i = 1:size(files);
name = files{i};
file = strcat('D:\words',name);
x = VideoReader(file.avi); %NOT SURE FROM THIS LINE%
v = read(x)
name = strcat(name,'.mat');
save(name,'v');
end
You don't need an additional function like fuf to get a list of file names.
If all your files are in "D:\words" (i.e. not in a bunch of sub-directories, which would complicate things), you can just use things like ls to fetch a list of all the avi files.
This is not the most elegant way of doing it (hard coding the directory and not using things like fullfile), but hopefully it's relatively easy to understand what's going on:
% use ls or dir to specifically match *.avi files
files = ls('D:\words\*.avi')
% note that size can return more than one value
% hence size(files,1)
for n = 1:size(files,1);
filename = files(n,:); % pick one file
% assuming this works - you might want to do some error checking
x = VideoReader(filename);
v = read(x);
% now we just want the name minus the ext
[pathstr,name,ext] = fileparts(filename);
fout = ['D:\words\',name,'.mat'];
save(fout,'v');
end
Your variable file is likely a string, not a structure:
...
file = strcat('D:\words',name);
x = VideoReader(file);
...
Or maybe this if the files in your cell array don't have extensions:
...
file = strcat('D:\words',name);
x = VideoReader([file '.avi']);
...
If your fuf function returns files that are not AVI movies, you'll need to do more work.
I wish to read files from a directory and iteratively perform an operation on each file. This operation does not require altering the file.
I understand that I should use a for loop for this. Thus far I have tried:
FILES = ls('path\to\folder');
for i = 1:size(FILES, 1);
STRU = pdbread(FILES{i});
end
The error returned here suggests to me, a novice, that listing a directory with ls() does not assign the contents to a data structure.
Secondly I tried creating a file containing on each line a path to a file, e.g.,
C:\Documents and Settings\My Documents\MATLAB\asd.pdb
C:\Documents and Settings\My Documents\MATLAB\asd.pdb
I then read this file using the following code:
fid = fopen('paths_to_files.txt');
FILES = textscan(fid, '%s');
FILES = FILES{1};
fclose(fid);
This code reads the file but creates a newline where a space exists in the pathway, i.e.
'C:\Documents'
'and'
'Setting\My'
'Documents\MATLAB\asd.pdb'
Ultimately, I then intended to use the for loop
for i = 1:size(FILES, 1)
PDB = pdbread(char(FILES{i}));
to read each file but pdbread() throws an error proclaiming that the file is of incorrect format or does not exist.
Is this due to the newline separation of paths when the pathway file is read in?
Any help or suggestions greatly apppreciated.
Thanks,
S :-)
First Get a list of all files matching your criteria:
( in this case pdb files in C:\My Documents\MATLAB )
matfiles = dir(fullfile('C:', 'My Documents', 'MATLAB', '*.pdb'))
Then read in a file as follows:
( Here i can vary from 1 to the number of files )
data = load(matfiles(i).name)
Repeat this until you have read all your files.
A simpler alternative if you can rename your files is as follows:-
First save the reqd. files as 1.pdb, 2.pdb, 3.pdb,... etc.
Then the code to read them iteratively in Matlab is as follows:
for i = 1:n
str = strcat('C:\My Documents\MATLAB', int2str(i),'.pdb');
data = load(matfiles(i).name);
% use our logic here
% before proceeding to the next file
end
I copy this from yahoo answers! It worked for me
% copy-paste the following into your command window or your function
% first, you have to find the folder
folder = uigetdir; % check the help for uigetdir to see how to specify a starting path, which makes your life easier
% get the names of all files. dirListing is a struct array.
dirListing = dir(folder);
% loop through the files and open. Note that dir also lists the directories, so you have to check for them.
for d = 1:length(dirListing)
if ~dirListing(1).isdir
fileName = fullfile(folder,dirListing(d).name); % use full path because the folder may not be the active path
% open your file here
fopen(fileName)
% do something
end % if-clause
end % for-loop