Copied to clipboard

sed

`sed` is a popular text processing tool. It can be used to edit and transform text within text files, and supports a wide range of regular expression matching and substitution functionality.
For example: s/original text/replacement text/g

Examples

  1. Replace text within a file:
sed 's/original text/replacement text/g' file.txt
  1. Display only odd-numbered lines:
sed -n '1~2p' file.txt
  1. Delete a specified line within a file:
sed -i '2d' file.txt
  1. Display lines within a file that match a pattern:
sed -n '/pattern/p' file.txt
  1. Display lines within a file that do not match a pattern:
sed -n '/pattern/!p' file.txt
  1. Display all lines from a file starting from line n:
sed -n 'n,$p' file.txt
  1. Insert a new line before line n of a file:
sed -i 'n i new line' file.txt
  1. Insert a new line after line n of a file:
sed -i 'n a new line' file.txt
  1. Delete lines within a file that match a pattern:
sed -i '/pattern/d' file.txt
  1. Replace all occurrences of text within a file with new text:
sed -i 's/original text/new text/g' file.txt

Understanding the -i Option

When the sed command is used with the -i option, sed will create a backup file of the original file being edited with the extension you provide. Then, sed will write the modified content to the original file, effectively modifying the file in place.

For example, suppose there is a file named example.txt, and you want to use sed to edit the file and create a backup file during the modification process. You can use the following command:

sed -i.bak 's/foo/bar/g' example.txt

In this command, -i.bak indicates that a backup file named example.txt.bak will be created during the editing process, and 's/foo/bar/g' indicates that all occurrences of "foo" within the file should be replaced with "bar". This operation will modify the example.txt file directly, and backup the original content to example.txt.bak.

Note that while the -i option can be a convenient way to perform editing operations, it should be used with caution, especially when working with important files. Careless use of the -i option can result in data loss or irreversible changes. When using the -i option, it is recommended to backup important files beforehand so that you can revert to the previous state if necessary.