How to delete or add line by sed

Delete a line

To delete a line from a file using sed, you can use the following command:

sed -e '/pattern/d' file

Where pattern is the text that you want to delete. For example, to delete all lines that contain the word “hello”, you would use the following command:

sed -e '/hello/d' file

Add a line

To add a line to a file using sed, you can use the following command:

sed -i '$a line_to_add' file

Where line_to_add is the text that you want to add. For example, to add the line “This is a new line” to the end of the file, you would use the following command:

sed -i '$a This is a new line' file

The -i flag tells sed to edit the file in place. This means that the original file will be overwritten with the new contents. If you do not want to overwrite the original file, you can use the -n flag to prevent sed from printing the output to the screen.

Additional examples

Here are some additional examples of how to use sed to delete or add lines to a file:

  • To delete all lines that start with the number 1, you would use the following command:
sed -e '/^1/d' file
  • To add a line after the line that contains the word “hello”, you would use the following command:
sed -i '/hello/a line_to_add' file
  • To delete the first 5 lines of a file, you would use the following command:
sed -e '1,5d' file
  • To add 3 blank lines to the end of a file, you would use the following command:
sed -i '$i\
\
\
' file