Mastering the sed Command with Tips, Tricks, and Examples

Text Transformation Wizardry


Introduction

The sed command, short for “stream editor”, is a powerful tool in Linux that allows you to perform fundamental text transformations on an input stream, such as a file or input from a pipeline. This blog post will explore some of the most common uses of the sed command and provide examples and tips to help you use it more effectively.

Replacing text

One of the most common uses of the sed command is to replace text in a file. For example, to replace all occurrences of the word “old” with the word “new” in a file called “file.txt”, you can use the following command:

replacing-text-before

sed 's/old/new/g' file.txt

replacing-text-after

Deleting text

Another common use of sed is to delete specific lines or text from a file. For example, to delete all lines that contain the word “delete” in a file called “file.txt”, you can use the following command:

deleting-text-before

sed '/delete/d' file.txt

deleting-text-after

Inserting text

sed can also be used to insert text at a specific line number. For example, to insert the text “new line” at line 5 in a file called “file.txt”, you can use the following command:

inserting-text-before

sed -n 's/.*\([A-Za-z0-9._%+-]*@[A-Za-z0-9.-]*\.[A-Za-z]*\).*/\1/p' file.txt

inserting-text-after

Tips and Tricks

When working with sed, it’s important to remember that it can be used to make changes in place, save changes to a new file, or even be used in combination with other commands. For example, you can use the -i option to make changes to a file in place, or you can use the > operator to save the output of a sed command to a new file.

I am gonna use the above example. After executing the last command we can see that the file remains unchanged.

tips

Now after executing the same sed command but with -i option, we will see that the file is changed:

tips

Conclusion

In conclusion, sed command is a powerful tool for performing basic text transformations on the input stream, it can be used for replacing, deleting, and inserting text, and even advanced usage with regular expression. By using the above examples and tips, you can use sed more effectively to automate your workflow and manage your files.

Thank you for reading 🧑‍💻

Stay tuned for more 🚀

✌️ and logout

Buy Me A Coffee

Plamen Ivanov
Plamen Ivanov
DevOps Engineer

Python & Bash Automation Ninja | Gopher Rookie on the Rise