Advanced sed Substitution Techniques
Capturing Groups
sed
allows you to use capturing groups to reference parts of the matched pattern in the replacement string. Capturing groups are defined using parentheses ()
in the pattern.
Example:
sed 's/\([0-9]\{3\}\)-\([0-9]\{3\}\)-\([0-9]\{4\}\)/(\1) \2-\3/' input_file.txt
In this example, the phone number format 123-456-7890
is captured in three groups: \1
(area code), \2
(prefix), and \3
(line number). The replacement string uses these captured groups to rearrange the format to (123) 456-7890
.
Conditional Substitutions
sed
also supports conditional substitutions, where the replacement is only performed if a certain condition is met. This is done using the t
command.
Example:
sed '/^#/!s/old_string/new_string/g' input_file.txt
In this example, the substitution is only performed on lines that do not start with a #
(i.e., non-comment lines).
In-Place Editing
By default, sed
outputs the modified text to the console. To perform in-place editing and modify the original file, you can use the -i
option.
Example:
sed -i 's/old_string/new_string/g' input_file.txt
This will replace all occurrences of old_string
with new_string
in the input_file.txt
file.
Multiline Substitutions
sed
can also handle multiline substitutions using the newline character \n
in the replacement string.
Example:
sed 's/pattern1/replacement1\nreplacement2/g' input_file.txt
This will replace each occurrence of pattern1
with two lines: replacement1
and replacement2
.
These advanced techniques allow you to perform more complex and powerful text manipulations with sed
, tailoring the substitutions to your specific needs.