sed

The sed command (short for "stream editor") is a powerful utility for text manipulation in Linux and Unix-like operating systems. It operates on a line-by-line basis, reading input and applying specified operations or transformations to the text. sed commands can be provided directly on the command line or stored in a script file for more complex operations.

Here are a few examples that illustrate the usage of sed:

  1. Find and Replace Text: The s command in sed is used to substitute text. For example, let's say we have a file called file.txt with the following content:

Hello, World!

We can use sed to replace "Hello" with "Hi" in the file:

sed 's/Hello/Hi/' file.txt

The output will be:

Hi, World!

In this example, the s/Hello/Hi/ command tells sed to substitute the first occurrence of "Hello" with "Hi" in each line of the input.

  1. Delete Lines: The d command in sed is used to delete lines. For example, let's consider the same file.txt as above, and we want to delete the line containing "Hello":

sed '/Hello/d' file.txt

The output will be empty, as the line containing "Hello" has been deleted.

  1. File Content Appending: The sed command can be used to append text to the end of each line in a file. For example, let's say we have a file called data.txt with the following content:

apple
banana
orange

We can use sed to append "(fruit)" to the end of each line:

sed 's/$/ (fruit)/' data.txt

The output will be:

apple (fruit)
banana (fruit)
orange (fruit)

In this example, the s/$/ (fruit)/ command appends " (fruit)" to the end of each line. The $ represents the end of the line.

These are just a few basic examples of using the sed command. sed provides a wide range of operations, including searching and replacing patterns, inserting and deleting lines, conditional operations, and more. Its capabilities can be further explored by referring to the documentation and learning about its various commands, options, and syntax.

Last updated