Need some help with re-formating a text.file using MATLAB?

Hi all,
I am quiet new in MATLAB, and I wish to have you guys help with re-formating a text file. A portion of the input text.file is below:
It mainly contains two keywords: DATE (year month day) and CHANGE (following be a variable like '10' and a number like 1.0). What I want is to have it converted is the text.file below:
The changes includes: 1. Reformat the Date to (day, month, year) and month to be words. 2. have the data after each CHANGE into a single row and add "good" if the variable is '10' while "bad" if the variable is '101'.
I have a crazy long text. file with these two keywords, it would be great if I could have MATLAB to do it. Any help or hint would be highly appreciated!

2 Comments

Remember that "guys" are male.
What have you done so far and which problem occurs?

Sign in to comment.

Answers (1)

Actually all you want to do is to replace the string
a = sprintf('''10''\n')
% by
b = sprintf('''10'' good ')
and
c = sprintf('''101''\n')
% by
d = sprintf('''101'' bad ')
The conversion of the first line is faster performed manually, if it is one file only, which is just "crazy" long.
If this matchs your problem:
s = fileread('YourFile.txt');
s = strrep(s, sprintf('''10''\n'), sprintf('''10'' good '));
s = strrep(s, sprintf('''101''\n'), sprintf('''101'' bad '));
[fid, msg] = fopen('NewFile.txt', 'w');
assert(fid > 0, msg);
fwrite(fid, s, 'char');
fclose(fid);

3 Comments

Hi Jan,
Appreciate your responsive help. Actually, I want to do two changes:
1. Date reformat. Have the DATE (year month day) to DATE (day month year). And the month to be corresponding words rather than number, say 10 to be Oct. I guess we should have a check function which can assign number 1 to 12 with a right words "Jan, Feb, ...Dec".
2. Sorry for being misleading. Since the variables after CHANGE are not just '10' and '101'. I have an array of variables ('10', '210', '12w', etc) to put 'good', while another array of variables ('101', '112w', etc.) to put 'bad'. So whenever the MATLAB meet 'variable' right after CHANGE, it should check whether this 'variable' is in good or bad groups.
Thanks again for your help!
Okay. What have you done so far and which problems occur?
"array of variables ('10', '210', '12w', etc) to put 'good', while another array of variables ('101', '112w', etc.) to put 'bad'." - Care for including all relevant information in the question. Otherwise posting an answer will waste time.
You can do text transformation of year and month number to month name abbreviation followed by year.
Or you can
char(datetime(YEARNUMBER, MONTHNUMBER, 1, 'Format', MMM yyyy))

Sign in to comment.

Categories

Find more on Data Import and Analysis in Help Center and File Exchange

Products

Asked:

on 24 Jun 2022

Commented:

on 24 Jun 2022

Community Treasure Hunt

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

Start Hunting!