Reading a directory location from text file and move to that directory.

3 views (last 30 days)
Hi all, I am new in matlab can you please help me with the following?:
I have a text file named config.txt with the following entries:
#--------------------------------Directories---------------------------
directory1 /media/fpdata/data1/ #data1
directory2 /media/fpdata/data2/ #data2
#----------------------------------------------------------------------
I would like to get the path for directory1 and change the directory inside my code to that directory.
I was trying the following with "grep":
config_file = 'config.txt'; %file with information
[fl, p] = grep('-u','directory1',config_file);
disp(p.result)
I got the following:
config.txt: directory1 /media/fpdata/data1/ #data1
from here I would like just to have the path: /media/fpdata/data1/ and then change to that directory
Maybe "grep" is not the right way to do that?
Thanks for your help!

Accepted Answer

Matthew Eicholtz
Matthew Eicholtz on 10 Mar 2016
Edited: Matthew Eicholtz on 10 Mar 2016
I would suggest trying to use textscan. The specifics of the input to the function will depend strongly on the setup of your text file. But, from what I can tell you have 3 columns (for instance, 'directory1' is in the first column, '/media/fpdata/data1/' is in the second column, '#data1' is in the third column).
In this case, try the following code:
fid = fopen('config.txt'); %this will open the file for read access
C = textscan(fid,'%s %s %s'); %scans the file, using '%s %s %s' as the FormatSpec
mask = strcmp(C{1},'directory1'); %finds matches in the first column for the string you want to find (in this case, 'directory1')
d = C{2}{mask}; %extracts the corresponding second column
Once you run the code above, you can change to the desired directory using:
cd(d);

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!