Text file modification (remove blank line)

I've a text file like this:
[TITLE]
-> blank line (I want remove) <-
[JUNCTIONS]
;ID Elev Demand Pattern
1 60 4 ;
2 40 4 ;
3 20 2 ;
4 40 0 ;
-> blank line (I want remove) <-
[RESERVOIRS]
;ID Head Pattern
5 100 ;
-> blank line (I want remove) <-
[TANKS]
;ID Elevation InitLevel MinLevel MaxLevel Diameter MinVol
-> blank line (I want remove) <-
[PIPES]
;ID Node1 Node2 Length Diameter Roughness
I have to remove blank line. Can someone help me?

 採用された回答

Walter Roberson
Walter Roberson 2016 年 5 月 17 日

0 投票

filecontent = fileread('YourFile.txt');
newcontent = regexprep(filecontent, '\n\n+', '\n');
fid = fopen('NewFile.txt', 'w');
fwrite(fid, newcontent);
fclose(fid);

3 件のコメント

Lunatix
Lunatix 2016 年 5 月 17 日
I don't know why doesn't work... I've tried long before ask... maybe there is something inside txt file. This is the original. Thanks a lot.
Walter Roberson
Walter Roberson 2016 年 5 月 17 日
filecontent = fileread('pressure.txt');
newcontent = regexprep(filecontent, {'\r', '\n\n+', '\n'}, {'', '\n', '\r\n'});
fid = fopen('new_pressure.txt', 'w');
fwrite(fid, newcontent);
fclose(fid);
Your original file is in dos format, using carriage return linefeed for the line terminator. The above code retains that. If you want it changed to just linefeed then use
newcontent = regexprep(filecontent, {'\r', '\n\n+'}, {'', '\n'});
Lunatix
Lunatix 2016 年 5 月 17 日
Thanks, it works perfectly!

サインインしてコメントする。

その他の回答 (0 件)

質問済み:

2016 年 5 月 17 日

コメント済み:

2016 年 5 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by