Mastering the sed Command: Tips, Tricks, and Examples for Text Transformation in Linux

k1lgor

k1lgor

Posted on January 28, 2023

Mastering the sed Command: Tips, Tricks, and Examples for Text Transformation in Linux

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
k1lgor
k1lgor

Posted on January 28, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related