How to replace a column in a txt file

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

回答(2 个)

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 个评论

"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.
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.

请先登录,再进行评论。

dpb
dpb 2014-3-20
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.

提问:

2014-3-20

Community Treasure Hunt

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

Start Hunting!

Translated by