Search code examples
stringmatlabcell

Search a text file for specific words using matlab and add string?


havent been able to find how to search for specific words in a text file anywhere, so here it goes, this is what I have now and just read and prints the entire text file. My Text file contains some words like:

K_G_M_H_NICK_MA,0,7500

P_SA_SWITCH_P_MPE_VL,0,1

If the string begins with 'K' it has to be write 'spec' in the end of the row whatever after K follows. Output has to be then

K_G_M_H_NICK_MA,0,7500 spec

If the string begins with 'P' it has to be write 'test' in the end of the row whatever after P follows. Output has to be then

P_SA_SWITCH_P_MPE_VL,0,1 test


Solution

  • MATLAB does not have this capability unfortunately. You don't have a choice but to read in each line of text, check for what you need then save a new file. You can use fgetl to query a line from a text file. Subsequent calls to fgetl reads the next lines and remembers the last line that you read from. You would use this in conjunction with your standard fopen and fclose to open up and close a file. You will need a reference to an open file with fopen before you use fgetl. Assuming that your file is called text.txt, simply read in the line, check the first character for your condition, then print out what you need at the end of the line should it match. It may be wise to also trim any whitespace before and after your code, so strtrim may be useful for you. Something like this should work, also assuming that you want to write to a new file called text_new.txt:

    fid = fopen('text.txt', 'r'); % Open up the file
    fidw = fopen('text_new.txt', 'w'); % Open up a new file to write
    
    tline = fgetl(fid); % Get the first line in the text file
    
    while ischar(tline) % As long as this line contains characters (i.e. not end of the file)
        % Trim the whitespace
        tline = strtrim(tline);
        % Check if first character is K or k, then write spec at the end of the line
        if tline(1) == 'k' || tline(1) == 'K'
            fprintf(fidw, '%s spec\n', tline);
        % Check if first character is P or p, then write test at the end of the line
        elseif tline(1) == 'p' || tline(1) == 'P'
            fprintf(fidw, '%s test\n', tline);
        % Write the line as is if no conditions match
        else
            fprintf(fidw, '%s\n', tline);
        end
    
        % Get the next line in the file
        tline = fgetl(fid);
    end
    
    % Close the files now
    fclose(fid);
    fclose(fidw);