how to add new column in existing text file?

I want to add new column in text files as their file names. I have 12000 files and i want to update them with their numbers. kindly help me to write a code for them. The desired text files should be as shown
ss.jpg

2 Comments

Ah, so you did post it as a separate question. Same question here: what have you tried so far? Try splitting a problem into solvable parts.
on the left is my input file and output file shown on the right. I add new column by using Excel but I have more than 12K files and I want to do the same with all of them with Matlab. can you write a code for this problem?

Sign in to comment.

 Accepted Answer

Bhaskar R
Bhaskar R on 20 Jan 2020
Edited: Bhaskar R on 20 Jan 2020
for ii = 1:12000
filename = [num2str(ii), '.txt']; % your file names as 1, 2.. .txt
mat = readmatrix(filename); % get file data
mat = [repmat(ii, size(mat, 1), 1), mat]; % append filename value to data
writematrix(mat, filename, 'Delimiter',' '); % write file with name
end
Hope this works for you !!

7 Comments

I hope so but it shows this error
Error using readmatrix (line 146)
Unable to find or open '1.txt'. Check the path and filename or file permissions.
Error in add_column (line 6)
mat = readmatrix(filename); % get file data
You need to adapt the code to make sure it generates the path to your files.
thank you so much @Rik, @Walter and special thanks to @bhaskar. It works now.
Hi @Rik,
I have a question. Let's say that I have a file or a series of files that's inputted into a table. I want to grab the year from the filename (e.g. temp_summary.05.month_year.txt), how can I adjust the code you suggested to do that and add it to a new column?
filename = 'temp_summary.05.08_2011.txt';
%more general form
[~, basename] = fileparts(filename);
nameparts = regexp(basename, '\.', 'split');
dateparts = regexp(nameparts{end}, '_', 'split');
year_str = dateparts{end}
year_str = '2011'
%special case where the year is the last thing after _
[~, basename] = fileparts(filename);
dateparts = regexp(basename, '_', 'split');
year_str = dateparts{end}
year_str = '2011'

Sign in to comment.

More Answers (0)

Categories

Asked:

on 20 Jan 2020

Edited:

on 9 Nov 2023

Community Treasure Hunt

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

Start Hunting!