I would like to change the extension of several files.
I mean that in one directory a I have many files in type file1.out, file2.out, ..., file600.out.
I would like to rename these files to *.txt (I mean file1.txt, file2.txt, ..., file600.txt) in this directory with one command via MATLAB?
I mean I would like to change the extension of some files from *.out to *.txt files.
This code from here can be helpful:
% Get all text files in the current folder
files = dir('*.out');
% Loop through each file
for id = 1:length(files)
% Get the file name
[~, f,ext] = fileparts(files(id).name);
% change the extension
rename = strcat(f,'.txt') ;
movefile(files(id).name, rename);
end
Related
In my code I want the user to manually choose a folder of .wav files to process.
I used :
dname=uigetdir('C:');
%% dname gives the path to the folder directory and saves it as a variable
I know that you can use cd directory name and cd .. like in Linux with MATLAB, how do I detach the meaningful part of dname to be able to use the cd function?
For the looping through, I found a stackexchange answer that covered that.
files = dir('C:\myfolder\*.txt');
for k = 1:length(files)
load(files(k).name, '-ascii')
end
dname=uigetdir('C:');
cd(dname); %make current directory, the directory specified by the path
files=dir('*.wav'); %get all the .wav files in the folder
for k=1:length(files); % loop through the files 1:last.wav
audio=cell(1, length(files)); %preallocate a cell with the appropriate size
audio{k} = audioread(files(k).name); %input in the files
end %files struct can be called after the end
I have a lot of .fig files that are named like this: 20160922_01_id_32509055.fig, 20160921_02_id_53109418.fig and so on.
So I thought that I create a script that loop through all the .fig files in the folder and group(copy) them into another folder(s) based on the last number in the file name. The folder is created based on the id number. Is this possible?
I have been looking on other solutions involving looping through folders but I am totally fresh. This would make it easier for me to check the .fig files while I am learning to do other stuff in Matlab.
All is possible with MATLAB! We can use dir to get all .fig files, then use regexp to get the numeric part of each filename and then use copyfile to copy the file to it's new home. If you want to move it instead, you can use movefile instead .
% Define where the files are now and where you want them.
srcdir = '/my/input/directory';
outdir = '/my/output/directory';
% Find all .fig files in the source directory
figfiles = dir(fullfile(srcdir, '*.fig'));
figfiles = {figfiles.name};
for k = 1:numel(figfiles)
% Extract the last numeric part from the filename
numpart = regexp(figfiles{k}, '(?<=id_)\d+', 'match', 'once');
% Determine the folder we are going to put it in
destination = fullfile(outdir, numpart);
% Make sure the folder exists
if ~exist(destination, 'dir')
mkdir(destination)
end
% Copy the file there!
copyfile(fullfile(srcdir, figfiles{k}), destination)
end
Here's an example how to identify and copy the files. I'll let you do the for loop :)
>> Figs = dir('*.fig'); % I had two .fig files on my desktop
>> Basename = strsplit(Figs(1).name, '.');
>> Id = strsplit(Basename{1}, '_');
>> Id = Id{3};
>> mkdir(fullfile('./',Id));
>> copyfile(Figs(1).name, fullfile('./',Id));
Play with the commands to see what they do. It should be straightforward :)
I have a number of text files with no Sequential Order :
010010.txt 010030.txt 010070.txt
How could I change the file names to:
text01.txt text02.txt ....
Is it possible not to re writte over the old directory but create a new directory
I have used the following script but the result is that it is working fine but it goes from text001.txt to text021.txt to then text041.txt
any idea?
directory = 'C:\test\'; %//' Directory with txt files
filePattern = fullfile(directory, '*.txt'); %//' files pattern with absolute paths
old_filename = cellstr(ls(filePattern)) %// Get the filenames
file_ID = strrep(strrep(old_filename,'file',''),'.txt','') %// Get numbers associated with each file
file_ID_doublearr = str2double(file_ID)
file_ID_doublearr = file_ID_doublearr - min(file_ID_doublearr)+1
file_ID = strtrim(cellstr(num2str(file_ID_doublearr)))
str_zeros = arrayfun(#(t) repmat('0',1,t), 4-cellfun(#numel,file_ID),'uni',0) %// Get zeros string to be pre-appended to each filename
new_filename = strcat('file',str_zeros,file_ID,'.txt') %// Generate new filenames
cellfun(#(m1,m2) movefile(m1,m2),fullfile(directory,old_filename),fullfile(directory,new_filename)) %// Finally rename files with the absolute paths
That looks pretty complicated. I would simply make a system call to move all of the files to a new directory, then sequentially rename each file one at a time with additional system calls. It also looks like you're using Windows, so I'll provide a solution for that platform. You have the beginning right where you are reading in the files from a source directory.
directory = 'C:\test\'; %// Directory with txt files
directoryToCopyOver = 'C:\out\'; %// Directory where you want to copy the files over
%// Copy source directory to target directory
system(['xcopy ' directory ' ' directoryToCopyOver]);
filePattern = fullfile(directoryToCopyOver, '*.txt'); %//' files pattern with absolute paths
names = dir(filePattern); %// Find all files with above pattern
%// For each file we have...
for idx = 1 : numel(names)
name = names(idx).name; %// Get a name of a file
%// Rename this file to textxx.txt
outName = sprintf('text%2.2d.txt', idx);
%// Call system and rename the file
system(['ren ' directoryToCopyOver name ' ' directoryToCopyOver outName]);
end
Some important things to note is that I use system to make system calls to your Windows command prompt. I use xcopy to copy a whole directory from one point to another. In this case, this would be your source directory over to a new target directory. After I do this, I invoke MATLAB's dir to determine all of the file names that match the particular pattern you have laid out, which is all of the text files.
Then, for each text file name we have, we read in this name, then create an output name of type textxx.txt, where xx is a number starting from 1 to as many text files as we have, and then I invoke the Windows command prompt command ren to rename the file from the original name to the new name. Also, take a look at sprintf from MATLAB. It is designed to create strings using formatting delimiters. If you see how I called it, %2.2d means that I am expecting the number to be two digits long, and should the number be less than two digits, fill the spaces with a zero. If you want to increase the amount of digits, simply add more to each place. For example, if you want to have 4 digits, do %4.4d, and so on. This will properly create the right string so that we can rename the right file in this new directory.
Hope this helps!
Hi I'm trying to create a matlab script in a way that it reads all files in a directory and launches a different command for every file extension.
I have:
teqc1.azi
teqc1.ele
teqc1.sn1
teqc2.azi
teqc****
what i need is that script reads the files and launches recursively the command:
`teqc1.azi -> plot_compact_2(teqc1.azi)`
`teqc1.ele -> plot_compact_2(teqc1.ele)`
`teqc1.sn1 -> plot_compact_2(teqc1.sn1)`
`teqc**** -> plot_compact_2(teqc****)`
This is what I've come up to right now:
function plot_teqc
d=dir('*'); % <- retrieve all names: file(s) and folder(s)
d=d(~[d.isdir]); % <- keep file name(s), only
d={d.name}.'; % <- file name(s)
nf=name(d);
for i=1:nf
plot_compact_2(d,'gps');
% type(d{i});
end
Thanks
Then you'll need the dir function to list the folder contents and the fileparts function to get the extensions.
You can also have a look at this question to see how to get a list of all files in a directory that match a certain mask.
So:
% get folder contents
filelist = dir('/path/to/directory');
% keep only files, subdirectories will be removed
filelist = {filelist([filelist.isdir] == 0).name};
% loop through files
for i=1:numel(filelist)
% call your function, give the full file path as parameter
plot_compact_2(fullfile('/path/to/directory', filelist{i}));
end
i have thousand files in a folder, however, i only need to extract out hundred files from the folder according to the filename listed in a text file into new folder. The filenames in text file is listed as a column..is that possible to be run by using matlab?what is the code shall i need to write? Thanks.
example:
filenames.txt is in the C:\matlab
folder include thousand files is named as BigFiles also in C:\matlab
files to be extracted from BigFiles folder is listed in column as below:
filenames.txt
a1sndh
sd3rfe
rgd4de
sd5erw
please advise...thanks...
Enumerate all files in a folder of a specific type (if needed) using:
%main directory to process
directory = 'to_process';
%enumerate all files (.m in this case)
files = dir(fullfile(directory,'*.m'));
numfiles = length(files);
fprintf('Found %i files\n',numfiles)
Then you could load the single column using one of the many file I/O functions in Matlab.
Then just loop through all the input names and check it's name against all the read in files (files{i}.name), and if so, move it.
EDIT:
From what I understood, you are looking for a solution along the lines:
filenames.txt
a.txt
b.txt
c.txt
.
.
.
moveMyFiles.m
%# read filenames listed in a text file
fid = fopen('C:\matlab\filenames.txt');
fList = textscan(fid, '%s');
fList = fList{1};
fclose(fid);
%# source/destination folder names
sourceDir = 'C:\matlab\BigFiles';
destDir = 'C:\matlab\out';
if ~exist(destDir,'dir')
mkdir(destDir);
end
%# move files one by one
for i=1:numel(fList)
movefile(fullfile(sourceDir,fList{i}), fullfile(destDir,fList{i}));
end
You can replace the MOVEFILE function by COPYFILE if you simply want to copy the files instead of moving them...