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:
Find and Replace Text: The
scommand insedis used to substitute text. For example, let's say we have a file calledfile.txtwith the following content:
Hello, World!We can use sed to replace "Hello" with "Hi" in the file:
sed 's/Hello/Hi/' file.txtThe 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.
Delete Lines: The
dcommand insedis used to delete lines. For example, let's consider the samefile.txtas above, and we want to delete the line containing "Hello":
sed '/Hello/d' file.txtThe output will be empty, as the line containing "Hello" has been deleted.
File Content Appending: The
sedcommand can be used to append text to the end of each line in a file. For example, let's say we have a file calleddata.txtwith the following content:
apple
banana
orangeWe can use sed to append "(fruit)" to the end of each line:
sed 's/$/ (fruit)/' data.txtThe 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