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 Kommentare

@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.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

KSSV
KSSV am 11 Mär. 2019
Bearbeitet: KSSV am 11 Mär. 2019
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 Kommentare

RR RR
RR RR am 11 Mär. 2019
Bearbeitet: RR RR am 11 Mär. 2019
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....

Melden Sie sich an, um zu kommentieren.

Stephen23
Stephen23 am 12 Mär. 2019
Bearbeitet: Stephen23 am 12 Mär. 2019
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.

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Produkte

Tags

Gefragt:

am 11 Mär. 2019

Bearbeitet:

am 12 Mär. 2019

Community Treasure Hunt

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

Start Hunting!

Translated by