Text Manipulation With the Sed Command | Bash

Text processing with sed (stream editor) in Bash is a powerful and efficient way to manipulate and transform text. sed operates on a line-by-line basis, making it suitable for processing large amounts of text data. Following some fundamental sed commands and provide examples to illustrate their usage.

Basic sed Syntax:
sed OPTIONS 'COMMAND' FILE
  1. OPTIONS:Optional flags to modify sed behavior.
  2. COMMAND:sed command or script enclosed in single quotes.
  3. FILE:Input file or stream.

Basic sed Commands

Substitution (s command):
sed 's/pattern/replacement/' input.txt
Example: Replace "apple" with "orange" in a file.
sed 's/apple/orange/' fruits.txt
Print (p command):
sed -n '2p' input.txt
Example: Print the second line of a file.
sed -n '2p' data.txt
Delete (d command):
sed '3d' input.txt
Example: Delete the third line of a file.
sed '3d' data.txt
Append (a command):
sed '/pattern/a\new line' input.txt
Example: Append a new line after lines containing a specific pattern.
sed '/apple/a\This is a new line' fruits.txt
Insert (i command):
sed '2i\new line' input.txt
Example: Insert a new line before the second line.
sed '2i\This line is inserted before the second line.' data.txt

Advanced sed Examples

Global Substitution (g flag):
sed 's/pattern/replacement/g' input.txt
Example: Replace all occurrences of "apple" with "orange" in a file.
sed 's/apple/orange/g' fruits.txt
In-place Editing (-i option):
sed -i 's/pattern/replacement/' input.txt
Example: Modify a file in-place by replacing "apple" with "orange."
sed -i 's/apple/orange/' fruits.txt

Using Regular Expressions

sed -n '/^pattern/p' input.txt
Example: Print lines starting with a specific pattern.
sed -n '/^start/p' data.txt

Conclusion

sed is a command-line stream editor in Bash that excels in complex text processing tasks. It operates on a line-by-line basis, allowing users to perform actions such as substitution, deletion, insertion, and pattern matching, making it a powerful tool for efficiently manipulating and transforming text data. With its concise syntax and versatile commands, sed is widely used for automating intricate text-editing operations in shell scripts and command-line environments.