Replace a block of strings in a text file with another string
Mostra commenti meno recenti
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.
Risposte (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 Commenti
KSSV
il 11 Mar 2019
You can follow the same for other.......as you have indices for ADDRESS..you can get indices for the next line....
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.
Categorie
Scopri di più su Characters and Strings in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!