One wonderful example is
sed uses a temporary file to actually save the contents and then replaces the original file. For example, you can do a simple testing to find this.
This is a test file.
ls -li to check the inode number.
ls -li test
2368770 -rw-r--r-- 1 root root 22 Sep 12 08:46 test
Now, issue the below
sed command to add a blank line.
sed -i 's/2/B/' test
After changing the file, issue the
ls command again and check the inode number.
ls -li test
2368753 -rw-r--r-- 1 root root 22 Sep 12 08:48 test
We can see that the inode number has infact changed. So instead of copying to the same file
sed creates a new temporary file and copies the contents to the new temp file and then deletes the original file and renames the tmp file in sync with the original file which is one reason why the file operations are really faster.
Quoting from wikipedia page,
sed is a line-oriented text processing utility: it reads text, line by
line, from an input stream or file, into an internal buffer called the
pattern space. Each line read starts a cycle. To the pattern space,
sed applies one or more operations which have been specified via a sed
script. sed implements a programming language with about 25 commands
that specify the operations on the text. For each line, after running
the script sed ordinarily outputs the pattern space (the input line as
modified by the script) and begins the cycle again with the next line.
To understand more on the pattern space and hold space concepts of
sed, you should read the answer here.
When sed reads a file line by line, the line that has been currently
read is inserted into the pattern buffer (pattern space). Pattern
buffer is like the temporary buffer, the scratchpad where the current
information is stored. When you tell sed to print, it prints the
Hold buffer / hold space is like a long-term storage, such that you
can catch something, store it and reuse it later when sed is
processing another line. You do not directly process the hold space,
instead, you need to copy it or append to the pattern space if you
want to do something with it.