In this article, you’ll learn to read a text file line by line, replace words in a line, and process every single line of the file. Specifically, you will learn:

  • to read a text file using fgetl
  • to use strrep to replace a word in a text
  • useful MATLAB commands to process a line

How to Read a Text File in MATLAB

Structure to Read a File

in MATLAB, you can use the fopen MATLAB command to open any kind of file you want (which includes .m files).

In order to read the file you open using fopen, you have to read it from start to end. This means using a while loop that will end once the file has been read entirely.

In that loop, you can use the fgetl MATLAB command to read a line of this file.

Here’s how to do that:

fid = fopen(fileName); % open the file
while ~feof(fid) % feof(fid) is true when the file ends
      textLineEntry = fgetl(fid) % read one line
end
fclose(fid); % close the file

In the code above, the variable «textLineEntry» takes sequentially the value of every line using the fid argument output by the fopen MATLAB command.

Example of Reading a Text by Line by Line

Let’s take the example of the following file:Example of file to read in MATLAB

  • Displaying every line: the name of this file is “fileToRead.txt”: therefore, we can use the previous code and replace the “fileName” variable with its string value:
    fid = fopen('fileToRead.txt');
    while ~feof(fid)
          textLineEntry = fgetl(fid)
    end
    fclose(fid);

    If you run the code above, you should see the following in your workspace:example of reading a text file line by line in matlab

  • Storing every line: If you want to read every line of your text file and save all of them into a variable, you can do that by defining a cell array, for example. Let’s initialize an empty variable and add a cell containing the text of every new line you read. Here’s what the code would look like:
    textLineEntryCellArray = [];
    fid = fopen('fileToRead.txt');
    while ~feof(fid)
          textLineEntry = fgetl(fid);
          textLineEntryCellArray = [textLineEntryCellArray {textLineEntry}];
    end 
    fclose(fid);

    In our case, the “textLineEntryCellArray” variable contains 3 cells, with each containing a line of the text file:
    import text file into matlab line by line

MATLAB String: Replace a Word in a Text

Use Strrep to Replace a Word

Using the MATLAB command strrep, you can replace a word in a line that you extracted from a text file.

Here’s how to use that command:

textLineEntryUpdated=strrep(textLineEntry, oldText, newText);

Simple Example

Let’s say that we want to modify the text from the file “fileToRead.txt” by replacing the colons in that file with arrows:

fid = fopen('fileToRead.txt');
while ~feof(fid)
      textLineEntry = fgetl(fid);
      textLineEntryUpdated = strrep(textLineEntry, ':', ' ->')
end
fclose(fid);

You should get the following in your workspace:

replace a word in every line of a text file

Copy and Modify a File

You might want to apply some of the modifications to your file and keep a copy of it.

You can do this by following these steps:

  1. Open a new file: using the MATLAB command fopen using a different name than the already existing file (which will be the modified file name). This would be:
    fidOut = fopen('modifiedTextToRead.txt', 'w');
  2. Print the modifications: after having modified the line using the strrep MATLAB command, you can use fprintf. Just be careful to use that command on the right text file, which means using the “fidOut” argument:
    textLineEntryUpdated = strrep(textLineEntry, ':', ' ->');
    fprintf(fidOut, '%s\n', textLineEntryUpdated));

Here’s the entire code to create a new modified file:

fidOut = fopen('modifiedTextToRead.txt', 'w');
fidIn = fopen('fileToRead.txt');
while ~feof(fidIn)
      textLineEntry = fgetl(fidIn);
      textLineEntryUpdated = strrep(textLineEntry, ':', ' ->');
      fprintf(fidOut, '%s\n', textLineEntryUpdated);
end
fclose(fidIn);
fclose(fidOut);

You should then have a new file called “modifiedTextToRead.txt”:

example of modifying a text file using fgetl

Processing a Line in a File

Separate the Words in a Line with Strsplit

Now that we’ve seen how to process a file line by line, let’s see how to process a line word by word.

Here, we will use the MATLAB command strsplit, which works as follows:

C = strsplit(textLineEntry, delimiter);

The «textLineEntry» variable is separated in a cell array. Every cell of that array is delimited by the delimiter in the variable «textLineEntry.»

In other words, if the delimiter is a blank space, we will have every word of the line contained in a cell array:

words = strsplit(textLineEntry, ' ');

Then, you can access every word by using braces. For example:

textLineEntry = 'Line 1: First line of this file';
words = strsplit(textLineEntry, ' ')

In MATLAB, we get:

separate words in a line using strsplit

Use Strtok to Cut a Line in Half

You can also use the strtok MATLAB command to separate the line into 2 parts:

[token, remain] = strtok(textLineEntry, delimiter);

For example, let’s say we want to separate a line by what is before the “:” and what is after, then we can do:

textLineEntry = 'Line 1: First line of this file';
[token, remain] = strtok(textLineEntry, ':');

In MATLAB, we get:

strtok example to separate a line into 2 parts

Searching for a Keyword in the Line

There are several ways that you can look for a word in a line.

  • Using strcmp: with the following:

    sameWords = strcmp(word1, word2) % sameWords is a boolean value

    if word1 and word2 are identical, sameWords will be 1 and 0 otherwise. If you want to know whether a word is in a line, then use strsplit to separate the words in the line and use strcmp in a for loop.

  • Using strfind: the MATLAB command strfind can indicate if a string is contained in another. If that’s not the case, then the output of that command will be empty. You just have to look at whether the strfind output is empty:

    keywordPresent = ~isempty(strfind(textLineEntry, keyword));

    For example, if we look for the word “of” in the first line of the text file:

    keyword = 'of';
    textLineEntry = 'Line 1: First line of this file';
    keywordPresent = ~isempty(strfind(textLineEntry, keyword))

    We get:
    example of finding a word text

Key takeaways:

  • Read a text file line by line using:

    while ~feof(fid)
          textLineEntry = fgetl(fid)
    end
  • Store every line of the text file into a variable using a cell array:

    textLineEntryCellArray = [];
    fid = fopen('fileToRead.txt');
    while ~feof(fid)
          textLineEntry = fgetl(fid);
          textLineEntryCellArray = [textLineEntryCellArray {textLineEntry}];
    end 
    fclose(fid);
  • Replace a word in a line using the MATLAB command strrep:

    textLineEntryUpdated = strrep(textLineEntry, oldText, newText);
  • Read a line word by word using:

    words = strsplit(textLineEntry, ' ');
  • Cut a line in half using the strtok MATLAB command:

    [token, remain] = strtok(textLineEntry, delimiter);
  • Query for the presence of a string value in a line using the strfind MATLAB command:

      keywordPresent = ~isempty(strfind(textLineEntry, keyword))