sed tutorial: sed in-place editing(-i option) with examples

Sed -i option, in-place editing of files, and can edit the operation file while the terminal does not output the sed execution result.

At the same time, while editing in place, the -i option also supports backing up the original file while editing. This can ensure that the original file content is restored when sed is misused.

Let’s see how to use the sed -i option to edit capabilities in-place. The following is the content of the test file used this time. We will use this file to demonstrate the in-place editing of sed for everyone.

1. This is a test file.
2. sed address and address range
3. sed action at a specific address or address range.
4. Sed action options: p, g, d …
5. sed stream
6. sed negating address range

Replacing in-place

In the following example, we will use the sed -i option to replace the content of the test file in-place.

➜  ~ sed -i 's/a test/a sed command test/' test.txt

Through the above sed in-place editing example, we found that the content of the original file has been replaced. But when we make mistakes, it is difficult to restore the original contents of the file.

Through the above sed in-place editing example, we found that the content of the original file has been replaced. But when we make mistakes, it is difficult to restore the original contents of the file.

Let’s take a look at how to use the sed -i option to back up the original file while editing in place.

Replacing in-place and backup

In the following example, we will use the sed -i option to replace the content of the test file in place and back up the original file content.

➜  ~ sed -i"_bak" 's/a test/a sed command test/' test.txt

Deleting in-place and backup

In the following example, we will use the sed -i option to delete specific lines of the test file in place and back up the original file contents.

➜  ~ sed -i"_del_bak" '5d' test.txt

Add a Comment

Your email address will not be published.