Replace a block of strings in a text file with another string

Hi all.
I have a very long text file. Ther are so much information in it. Within the text file, there are many addresses that are written in a specific format. The format of the addresses is as follows: we have a fixed string "ADDRESS" in the first line, in the second line I have variable (changing) strings "text1..." ,"text2...", etc (each text might have different lengths) which are the addresses. At the end of this line I have a fixed slash caharcter"/". Finaly, at the third line I have an empy line but is teminated with another slash"/". The following shows two instances of this address block format:
...
ADDRESS
text1 /
/
ADDRESS
text2 /
/
...
I would like to change (replace) any of the above blocks with the following "fixed" block
NUMBER
NOTAVAILIABLE/
Therfore my text file should replace all of those and show something like this:
...
NUMBER
NOTAVAILIABLE/
NUMBER
NOTAVAILIABLE/
...
I want to save the new file in a different text file. I really appreciate your help.

2 Comments

@RR RR: please upload a sample file by clicking the paperclip button. It does not have to be the whole file, just enough to include the relevant data.
@Stephen Cobeldick I have uploaded two files. A sample input file, and a desired output file. The program should read the input file and should reproduce something like the output file.

Sign in to comment.

Answers (2)

YOu should follow something like below:
fid = fopen('data.txt') ;
S = textscan(fid,'%s','delimiter','\n') ;
S = S{1} ;
fclose(fid) ;
idx = contains(S,'ADDRESS') ;
S(idx) = {'NUMBER'} ;
% Write to file
fid = fopen('new.txt','w');
fprintf(fid,'%s\n',S{:});
fclose(fid);

2 Comments

Thanks KSSV. But this one only replaces ADDRESS with NUMBER. It doesnot change the slash and "text1" ,"text2" ,.. to "NOTAVAILIABLE". Am I correct?
You can follow the same for other.......as you have indices for ADDRESS..you can get indices for the next line....

Sign in to comment.

One way is to use a regular expression, which even lets you keep the EOL characters exactly the same:
rgx = 'ADDRESS(\s+)[^/]+/\s*';
rpl = 'NUMBER$1NOTAVAILABLE';
str = fileread('Input_Text_File.txt');
str = regexprep(str,rgx,rpl);
[fid,msg] = fopen('test_out.txt','w');
fprintf(fid,'%s',str);
fclose(fid);
The test files are attached, you can see that test_out.txt is identical to your example output file.

Categories

Products

Tags

Asked:

on 11 Mar 2019

Edited:

on 12 Mar 2019

Community Treasure Hunt

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

Start Hunting!