How to insert new empty lines in middle of an exisiting text file

46 ビュー (過去 30 日間)
Omar Shehata
Omar Shehata 2017 年 8 月 25 日
編集済み: Guillaume 2017 年 8 月 25 日
Hello,
i have the following problem: I have a txt.file into which i want to add a couple of new empty lines at a certain position (row number).
Old Text File: Line1 Line2 Line3 Line4
New Txt File: Line1 Line2 New Empty Line New Empty Line Line3 Line4
Thanks for your help
  4 件のコメント
Kevin Xia
Kevin Xia 2017 年 8 月 25 日
How are you representing the new empty lines? With whitespace?
Omar Shehata
Omar Shehata 2017 年 8 月 25 日
with sprintf('\n');

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

回答 (2 件)

Kevin Xia
Kevin Xia 2017 年 8 月 25 日
Try using the functions importdata and strjoin with '\n' as the delimiter. importdata will give output a cell array that you can insert an extra row in. Something like:
rowNum=3;
textlines=[textlines(1:rowNum);sprintf('\n');textlines(rowNum+1:end)]
will insert a newline into the cell array at the desired row number. Strjoin can join the cell array together into a character array, which can be printed to a file using fopen and fprintf. Please see the documentation for these functions for more details.

Guillaume
Guillaume 2017 年 8 月 25 日
編集済み: Guillaume 2017 年 8 月 25 日
One of the many possible ways to do this:
filepath = 'c:\somewhere\somefile.txt;
contents = fileread(filepath);
lines = strsplit(contents, '\n', 'CollapseDelimiters', false);
newlines = [lines(1:2), {'', ''}, lines(3:end)]; %to insert two blank lines at line 3
newcontents = strjoin(newlines, '\n');
fid = fopen(filepath, 'w');
fwrite(fid, newcontents);
fclose(fid);

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by