I want to write data at the end of every nth line of a text file

4 views (last 30 days)
I have a long text file which contains several thousands of the following type of data
a0 =
333222
323312
310132
a1=
33222
323312
310132
a2=
133222
323312
310132
a3=
233222
323312
310132
a4=
303222
323312
310132
a5=
313222
323312
310132
a6=
323222
323312
310132
:
:
a2776=...
And I want to add at the end of evry 4th line a letter c and save back that modified file in txt format. After modification it should look like that
a0 =
333222
323312
310132c
a1=
33222
323312
310132c
a2=
133222
323312
310132c
a3=
233222
323312
310132c
a4=
303222
323312
310132c
a5=
313222
323312
310132c
a6=
323222
323312
310132c
:
:
:
a2776=...

Accepted Answer

Voss
Voss on 21 Jul 2024
str = readlines(filename);
str(4:4:end) = str(4:4:end) + "c";
writelines(str,filename)

where "filename" is the absolute or relative path to your text file, e.g., filename = 'C:\work\files\my_file.txt'.

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!