MATLAB: To replace a character AT A PARTICULAR POSITION in a Text FIle.

replace a character at specified position in a text file

I have a Text File containing many characters, I wish to modify one of those characters at a particular position
Suppose, I have a text file "1ABC.txt"
Contents of 1ABC.txt are as follows:
ADHKIGFJOFNDFBDKI
Now
from = {D,K,F};
to = {E,I,A};
position = {2,4,10};
For position in variable "position",
I have to check if the character at that position in 1ABC.txt is the same as in variable "from".
If that character is same , then I have to replace it with the character in variable "to".
Then I have to store this new line (after replacing original character in 1ABC.txt) in a different file "new.txt".
Then it will check for other positions in position variable and store the new line after replacement as a next line in the file "new.txt".
E.g. : Program will check if at the second position there is 'D' in 1ABC.txt.
Since, there is 'D' at second position of 1ABC.txt, so it will replace it with 'E'.
Save the text as new.txt after replacement and subsequent replacements as new line in "new.txt" so on loop will run …..

Best Answer

  • I see that you accepted 0% of the answers that were given to your 4 previous questions; please take a moment for reviewing these questions/answers and accept relevant answers.
    As mentioned in my comment below your question, working with memory would be much more efficient if you follow an iterative process. However, here is an example illustrating one way to achieve what you want using regular expressions:
    % - Read source file.
    buffer = fileread('1ABC.txt') ;
    % - Extract {string, from, to, position} from content => struct.
    pattern = '(?<string>^\S*).*?{(?<from>.*?)}.*?{(?<to>.*?)}.*?{(?<position>.*?)}' ;
    content = regexp(buffer, pattern, 'names') ;
    content.position = str2num(content.position) ;
    % - Replace characters when relevant.
    for k = 1 : 3
    if buffer(content.position(k)) == content.from(1+2*(k-1))
    buffer(content.position(k)) = content.to(1+2*(k-1)) ;
    end
    end
    % - Export to destination file.
    fid = fopen('new.txt', 'w') ;
    fwrite(fid, buffer) ;
    fclose(fid) ;
    Note that it would be possible to make the whole pattern matching and replacement as a single call to REGEXPREP I guess, but the pattern would be significantly more complicated.