Info

This question is closed. Reopen it to edit or answer.

Extracting Multiple .txt files contained in a folder to separate tabs in excel

1 view (last 30 days)
I have a series of .txt files contained in a file and would like to parse each .txt file and extract certain bits of information from these files. What i need is to open this folder and parse each .txt then export the important information to a tab in excel.
For example my file structure looks something like this:
File Folder: Mock_Folder
ABC_123.txt
DEF_456.txt
Lets say each .txt contains various information but i want to pull the specific line Dogs=number. How can i export the number of dogs from both ABC_123.txt and DEF_456.txt to two different tabs in excel?

Answers (2)

Prasad Mendu
Prasad Mendu on 6 Jul 2016
Edited: Prasad Mendu on 6 Jul 2016
Assuming that you would like to first scan the text files and then write the results into an excel file, first 'fopen' function should be used followed by 'textscan' and 'xlswrite' functions.
Text file can be open using the function 'fopen'. Documentation link for 'fopen':
Then the function 'textscan' can be used along with the format specification to scan your files.
More information on 'textscan' can be found at the link below:
After the text scan results are obtained, 'xlswrite' command can be used to write the results into different tabs of the excel file.
>>xlswrite(filename,matrixName,sheet) %third argument specifies the sheet to write into
Refer to the following link for more information on this:

Guillaume
Guillaume on 6 Jul 2016
One quick way:
folderpath = 'c:\some\mockfolder';
filelist = dir(fullfile(folderpath, '*.txt')); %get list of file
xlsfile = 'somefile.xlsx';
for file = filelist' %iterate over files;
filecontent = fileread(fullfile(folderpath, file.name)); %read whole file in one go
dogcount = str2double(regexp(filecontent, '(?<=Dogs=)\d+', 'match', 'once')); %get number of dogs (assuming integer)
[~, sheetname] = fileparts(file.name); %strip file extension
xlswrite(fullfile(folderpath, xlsfile), dogcount, sheetname);
end

Community Treasure Hunt

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

Start Hunting!