How to read from a *.txt file to assign variables and paths

조회 수: 10 (최근 30일)
Samuel
Samuel 2013년 7월 24일
I would like to read from a text file that has the format of the following:
BASEPATH="'/Users/asdf/xyz'"
FILENAME1="'HELLO.txt'"
FILENAME2="'GOODBYE.txt'"
XVALUE="1"
YVALUE="2"
The purpose is to use this as an input file to import other files, HELLO.txt and GOODBYE.txt (in the same directory - /Users/asdf/xyz), and assign values for a few variables (XVALUE = 1 and YVALUE = 2).
Any help will be appreciated. Thanks!

채택된 답변

Matt Kindig
Matt Kindig 2013년 7월 24일
편집: Matt Kindig 2013년 7월 24일
Easiest way is to parse with regular expressions and read into an output structure with named fields.
%read in file
str = fileread('/path/to/your/file.txt');
%extract fields and values
pieces = regexp(str, '(?<field>\w+)=(?<value>[^\n]+)', 'names');
out = struct(); %your variables
for k=1:length(pieces),
field = pieces(k).field;
val = pieces(k).value;
tf= ismember(val, char([34 39])); %remove " and ' from string
val = strtrim(val(~tf)); %also remove spaces
%try to convert to double. If successful, use converted value,
%otherwise use original (string) value
valn = str2double(val);
if ~isnan(valn), %conversion successful, use as numeric
val = valn;
end
%add to output structure
out.(field) = val;
end
  댓글 수: 4
Matt Kindig
Matt Kindig 2013년 7월 27일
To clarify, you want to combine together the contents of all files which have the same 4-letter combo immediately prior to the file extension? If so, this is a bit different than the posted question, so you're better off starting a new question in this forum.
Matt Kindig
Matt Kindig 2013년 7월 27일
In particular, there are several Linux tools that would probably be faster and better for this task. Also, this can probably be done quite efficiently in Perl.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by