What is sed pattern buffer?

Sed is known as Stream Editor, which is useful while working with text files.

In this shot, we will learn about the pattern buffer concept in Sed.

When we execute the sed command on any text file or input it does the following things:

  • Sed reads the input stream until it finds the new line character \n.
  • Then it will take all the data it read so far and place it into a buffer without newline character \n.
  • Most of the commands operate on this data present in the buffer.
  • This buffer is known as pattern buffer.

Let us take a look at an example to understand it better:

Example

In the following example, we are using a text file called data.txt, which has 9 lines. We can check the content using the below command in the below terminal, which prints the contents of the file data.txt:

cat data.txt

If you tried the above command, you must have seen the keyword Educative. We will try to modify the content of the file data.txt where Educative is present with EDUCATIVE using the sed command.

Try the below command to modify the content:

sed 's/Educative/EDUCATIVE/' data.txt

When you execute the above command,

  • sed reads the first line until the new line character \n and places it into the pattern buffer, where the sed command will replace the content with the given condition.
  • Insert the new line character at the end.
  • By default, sed will print the pattern buffer, but we can suppress this using the -n command with sed.
  • So, after executing this command, you can see the output with the modified content.
Terminal 1
Terminal
Loading...

Pattern buffer is useful for this type of case where we don’t want to modify the original file but we want to do some operation on the content and check the output if it meets our expectations.

Free Resources