Enhancing Skills

sed: Stream Editor for Filtering and Transforming Text

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:

sed [options] 'script' [file...]

Examples

  1. Substitute Text
   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):

   This is the old text.
   Another line with old text.

Sample Output:

   This is the new text.
   Another line with old text.
  1. Replace All Occurrences in Each Line
   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):

   This old text is old.

Sample Output:

   This new text is new.
  1. Delete Lines Matching a Pattern
   sed '/pattern/d' filename.txt

Description: Deletes lines that match the pattern “pattern” from filename.txt.

Sample File (filename.txt):

   This is a line.
   Remove this line.
   Another line.

Sample Output:

   This is a line.
   Another line.
  1. Insert Text Before a Line
   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):

   Before pattern
   This is the pattern line.
   After pattern

Sample Output:

   Before pattern
   new line
   This is the pattern line.
   After pattern
  1. Replace Text in Multiple Files
   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):

   old text here

Sample Output in file1.txt:

   new text here
  1. Print Lines Matching a Pattern
   sed -n '/pattern/p' filename.txt

Description: Prints only the lines that match the pattern “pattern” from filename.txt.

Sample File (filename.txt):

   Line 1
   Line 2 with pattern
   Line 3

Sample Output:

   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.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.