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.
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
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
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 -n 's/.*\([A-Za-z0-9._%+-]*@[A-Za-z0-9.-]*\.[A-Za-z]*\).*/\1/p' file.txt
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:
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