Cart 0
No products in the cart.

How to use the Linux sed Command ?

How to use the Linux sed Command ?

Linux sed command is a powerful tool used for text manipulation and to make changes to files in a Linux system. It stands for Stream EDitor and is used to search, find and replace text in a file. It is a very useful command for those who work with files and text in Linux environment. 

Here at Fixwebnode, we shall look into how to use the sed command in different Linux distributions. 

 

Options of the Linux sed Command

Linux sed command has many options that can be used for text manipulation. 

The following are the commonly used options:

  • -n: This option suppresses the default output of sed.
  • -e: This option allows you to run multiple sed commands.
  • -i: This option is used to edit files in-place.
  • -r: This option enables extended regular expressions in the sed command.
  • -f: This option reads sed commands from a file.
  • -d: This option is used to delete lines.
  • -s: This option is used to search and replace text.

 

Examples of using Linux sed Command

Now let's look at some examples of how to use the Linux sed command.

 

1. Print a specific line number:

To print a specific line number, use the following command:

$ sed -n 2p file.txt

This command will print the 2nd line of the file.txt.

 

2. Delete lines using a range:

To delete a range of lines, use the following command:

$ sed -i '4,7d' file.txt

This command will delete lines 4 to 7 from the file.txt.

 

3. Search and replace text:

To search and replace text, use the following command:

$ sed -i 's/oldtext/newtext/g' file.txt

This command will replace all occurrences of "oldtext" with "newtext" in the file.txt.

 

How to use Sed Command on Different Linux Distributions ?

To use the sed command on different Linux distributions, the basic syntax is the same; however, the options may differ. 

 

1. For example, in Ubuntu and Debian, the -i option is used with an argument "backup". To edit a file in-place, you can use the following command:

$ sed -i backup 's/oldtext/newtext/g' file.txt

 

2. In CentOS and Red Hat, the -i option is used without an argument. To edit a file in-place, you can use the following command:

$ sed -i 's/oldtext/newtext/g' file.txt

 

[Need Linux Support ? We can help you. ]

 



CONCLUSION

This article covers the Linux sed command and its options with examples. We also explained how to use the sed command on different Linux distributions. In fact, the sed command is a powerful tool for manipulating text and making changes to files in a Linux system.


icon

Sign up to Newsletter

...and receive a free support ticket.