Extracting rows from csv file which contain only certain text

4 views (last 30 days)
Hello, I have a csv file containing all the information I need. However, there are some rows I will not use in my data analysis. So I need to take out only certain rows I need, in order to have proper file to work with. The question is: If i want to extract all the rows which contain specific text in one of their columns, for instance 'Kitchen', and save only them to a new csv file, how do i do that?

Answers (1)

dpb
dpb on 6 Apr 2016
doc strfind
NB: there's no specific reason to make a new file unless you have other reasons besides doing the analysis; just read the data and select the desired subset in memory and do the analysis...certainly no need to
Open/Read/Close/Select/CreateOpenNew/Write/Close/Open/ReadSelected/Close/Analyze
when can simply
Open/Read/Close/Select/Analyze
  3 Comments
dpb
dpb on 6 Apr 2016
Given data array x containing the string from which you wish to find a particular match in one column it's a simple as
x=x(strfind(x(:,3),'kitchen'),:); % say it's column 3, fixup as needed
will leave you with the array containing only the rows in which there was the match. NB: strfind is case-sensitive so you either need to match the precise string or do something like
x=x(upper(strfind(x(:,3)),'KITCHEN'),:);
To write depends on the format you want and the content; the easy-to-use csvwrite will only operate on numeric data so you will probably have to use fprintf unless TMW has introduced some new, more generic i/o routines since R2012b which is the latest I have here.
Hope that helps...
Image Analyst
Image Analyst on 7 Apr 2016
Well, if you have a table variable, with some columns being strings and other columns being numbers, you can use writetable().
fprintf() is the most flexible though, but it take a few more steps than writetable.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!