Here are some advanced features of sed that enhance its text processing capabilities:
1. Addressing
You can specify line ranges or patterns to apply commands only to specific lines:
sed '1,5s/old/new/g' filename.txt # Replace in lines 1 to 5
sed '/pattern/s/old/new/g' filename.txt # Replace in lines matching 'pattern'
2. Hold Space
sed has a hold space that allows you to temporarily store text for later use:
sed -e '1h' -e '2G' filename.txt # Copy line 1 to hold space, then append it to line 2
3. Multiple Commands
You can execute multiple commands in a single sed invocation using -e or by separating commands with a semicolon:
sed -e 's/old/new/g' -e '2d' filename.txt
or
sed 's/old/new/g; 2d' filename.txt
4. Using Regular Expressions
sed supports extended regular expressions with the -E option, allowing for more complex pattern matching:
sed -E 's/(old|new)/replacement/g' filename.txt # Replace 'old' or 'new'
5. Conditional Execution
You can use the t command to branch based on whether a substitution was made:
sed '/pattern/{s/old/new/g; t; s/another/replace/g;}' filename.txt
6. Appending and Prepending
You can append or prepend text to lines:
sed '2a\This is appended text' filename.txt # Append after line 2
sed '2i\This is prepended text' filename.txt # Prepend before line 2
7. Using Shell Variables
You can use shell variables within sed commands:
var="replacement"
sed "s/old/$var/g" filename.txt
8. Reading from a File
You can read commands from a separate file using the -f option:
sed -f commands.sed filename.txt
These advanced features make sed a powerful tool for complex text processing tasks in scripts and command-line operations.
