sed: Stream Editor for Filtering and Transforming Text
August 12th, 2024 12:46 PM Mr. Q Categories: Command
The sed
command is a stream editor used for filtering and transforming text. It processes text line by line and can perform various editing tasks, such as substitutions, deletions, and insertions.
Command:
Copy001sed [options] 'script' [file...]
Examples
- Substitute Text
Copy001 sed 's/old/new/' filename.txt
Description: Replaces the first occurrence of “old” with “new” in each line of filename.txt
.
Sample File (filename.txt
):
Copy001 This is the old text.
002 Another line with old text.
Sample Output:
Copy001 This is the new text.
002 Another line with old text.
- Replace All Occurrences in Each Line
Copy001 sed 's/old/new/g' filename.txt
Description: Replaces all occurrences of “old” with “new” in each line of filename.txt
.
Sample File (filename.txt
):
Copy001 This old text is old.
Sample Output:
Copy001 This new text is new.
- Delete Lines Matching a Pattern
Copy001 sed '/pattern/d' filename.txt
Description: Deletes lines that match the pattern “pattern” from filename.txt
.
Sample File (filename.txt
):
Copy001 This is a line.
002 Remove this line.
003 Another line.
Sample Output:
Copy001 This is a line.
002 Another line.
- Insert Text Before a Line
Copy001 sed '/pattern/i\new line' filename.txt
Description: Inserts “new line” before lines that match the pattern “pattern” in filename.txt
.
Sample File (filename.txt
):
Copy001 Before pattern
002 This is the pattern line.
003 After pattern
Sample Output:
Copy001 Before pattern
002 new line
003 This is the pattern line.
004 After pattern
- Replace Text in Multiple Files
Copy001 sed -i 's/old/new/g' file1.txt file2.txt
Description: Replaces all occurrences of “old” with “new” in file1.txt
and file2.txt
. The -i
option edits files in place.
Sample File (file1.txt
):
Copy001 old text here
Sample Output in file1.txt
:
Copy001 new text here
- Print Lines Matching a Pattern
Copy001 sed -n '/pattern/p' filename.txt
Description: Prints only the lines that match the pattern “pattern” from filename.txt
.
Sample File (filename.txt
):
Copy001 Line 1
002 Line 2 with pattern
003 Line 3
Sample Output:
Copy001 Line 2 with pattern
The sed
command is a versatile tool for text processing, allowing for complex text manipulation in scripts and command-line operations.