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

Photo by RetroSupply on Unsplash

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

ยท

2 min read


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:

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

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:

sed '/delete/d' file.txt

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:

sed '5i new line' file.txt

Using Regular Expression (RegEx)

sed also has the ability to use regular expressions. For example, to extract all the email addresses from a file called "file.txt", you can use the following command:

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

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.

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

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

ย