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

3 次查看(过去 30 天)
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!

采纳的回答

Matthew Eicholtz
Matthew Eicholtz 2016-3-10
编辑:Matthew Eicholtz 2016-3-10
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);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by