sed (Stream Editor)
sed is a powerful stream editor used to perform basic text transformations on an input stream (a file or input from a pipeline). It is commonly used for text substitution, deletion, and insertion.
Basic Syntax
Commonly Used Options
-e script: Add the script to the commands to be executed.-f script-file: Add the contents of the script-file to the commands to be executed.-i[SUFFIX]: Edit files in place (makes backup if SUFFIX supplied).-n: Suppress automatic printing of pattern space.-r: Use extended regular expressions in the script.-s: Treat files as separate rather than as a single continuous long stream.-u: Load minimal amounts of data from the input files and flush the output buffers more often.
Common Commands
s/pattern/replacement/flags: Substitute pattern with replacement.d: Delete pattern space.p: Print pattern space.a\ text: Append text after the current line.i\ text: Insert text before the current line.c\ text: Replace the current line with text.y/source/dest: Transliterate characters in the pattern space.
Flags for s Command
g: Global replacement.p: Print the line if a replacement was made.w file: Write the result to a file.number: Replace only thenumberth occurrence.
Examples
Substitute Text
Replace the first occurrence of "foo" with "bar" in each line:
Replace all occurrences of "foo" with "bar" in each line:
Delete Lines
Delete lines containing "foo":
Delete the first line of the file:
Print Lines
Print lines containing "foo":
Print the first 10 lines of the file:
Insert and Append Text
Insert "Hello" before the first line:
Append "World" after the last line:
Replace Entire Line
Replace lines containing "foo" with "bar":
Transliterate Characters
Replace all occurrences of "a" with "A" and "b" with "B":
In-Place Editing
Replace "foo" with "bar" in the file and save changes:
Using a Script File
Create a script file script.sed with the following content:
Run sed with the script file:
Using Extended Regular Expressions
Replace all digits with "X":
Conclusion
sed is a versatile tool for text processing and can be used for a wide range of tasks, from simple substitutions to complex text manipulations. Understanding its options and commands allows for efficient and powerful text editing directly from the command line.