Skip to main content

Sed Recipes

Summary

Recipes for GNU sed (stream editor), which is a non-interactive command-line text editor.

What is sed? #

GNU sed, or the stream editor, is a command-line text processing tool that operates on streams of text input. It reads text from a specified source, applies specified editing commands, and then outputs the modified text.

sed is a powerful and versatile tool for text manipulation in Unix-like environments. Check the GNU sed cheat sheet for even more sed command examples.

Removing lines #

sed recipes for removing/deleting lines from a file following one or more expressions, invoked by the -e / --expression= operator.

sed does not remove the lines from the source file by default. Use the -i option with the sed command to work on the source file. Alternatively, use redirection to save the output to a new file, e.g. sed '1d' file > newfile.

Delete empty lines or blank lines:

$ sed '/^$/d' file

Delete lines that begin with a specified character, in this case “a”:

$ sed '/^a/d' file

Delete lines that end with a specified character, in this case “a”:

$ sed '/a$/d' file

Delete lines where contents are written in upper case or capital letters:

$ sed '/^[A-Z]*$/d' file

Delete lines that contain the pattern “foobar”:

$ sed '/foobar/d' file

Delete lines starting from a pattern till the last line

$ sed '/foobar/,$d' file

Further readings #

Sources and recommended, further resources on the topic:

Author

Jonas Jared Jacek • J15k

Jonas Jared Jacek (J15k)

Jonas works as project manager, web designer, and web developer since 2001. On top of that, he is a Linux system administrator with a broad interest in things related to programming, architecture, and design. See: https://www.j15k.com/

License

License: Sed Recipes by Jonas Jared Jacek is licensed under CC BY-SA 4.0.

This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. To give credit, provide a link back to the original source, the author, and the license e.g. like this:

<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/publications/sed-recipes">Sed Recipes</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-SA 4.0</a>.</p>

For more information see the DITig legal page.


“Users spend most of their time on other sites. This means that users prefer your site to work the same way as all the other sites they already know.”

Jakob Nielsen, Principal and Co-founder of the Nielsen Norman GroupJakob's Law of Internet User Experience, - IT quotes