How to replace a column in a txt file

8 views (last 30 days)
Marco
Marco on 20 Mar 2014
Edited: per isakson on 20 Mar 2014
Hi, I need to edit a specific column in a txt or xls file. I know the column number, I just need to replace it with new numerical values. Can I ask you how to do it? Thanks in advance Marco
ps. The txt file is like this
a 1
b 1
c 1 ....... I need to change "1" with other values every time the code opens the file

Answers (2)

per isakson
per isakson on 20 Mar 2014
Edited: per isakson on 20 Mar 2014
With xls-files it possible "to edit a specific column". See xlswrite, Write Microsoft Excel spreadsheet file.
Use the xlRange argument in
xlswrite(filename,A,xlRange)
And with a fixed format text file I assume it would be possible with a memmapfile and some coding effort. See Overview of Memory-Mapping, memmapfile, Create memory map to a file and sub2ind, Convert subscripts to linear indices
  2 Comments
dpb
dpb on 20 Mar 2014
"Possible", surely... :) Worth the effort??? That case can also be done simply by loading the file as character array and counting positions or just w/ strrep()
If were to use the Excel-like route I'd prefer to just use a text editor with a macro language in batch mode--almost any programming editor can do that.
per isakson
per isakson on 20 Mar 2014
Edited: per isakson on 20 Mar 2014
Agree, it's hard to imagine a use case, which makes the use of memmapfile worthwhile - a zillion huge files and edit a row rather than a column.
However, the option comes with xlswrite.

Sign in to comment.


dpb
dpb on 20 Mar 2014
Only practical way is to read into a cell array, modify the contents of the cells in column 2 as desired and write back out. Text files are sequential so processing columns basically doesn't happen except in memory.

Community Treasure Hunt

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

Start Hunting!