Advanced sed Substitution Techniques
While the basic substitution command s/pattern/replacement/
is a powerful tool, sed offers advanced substitution techniques that can significantly expand your text manipulation capabilities. In this section, we will explore some of these advanced techniques and their practical applications.
Capturing and Referencing Matched Patterns
Sed allows you to capture parts of the matched pattern using parentheses ()
and reference them in the replacement string using the special &
and \1
, \2
, etc. markers.
## Replace the first word in each line with "REPLACED"
sed 's/\w+/REPLACED/' input_file.txt
## Capitalize the first letter of each line
sed 's/^./\U&/' input_file.txt
## Swap the first two words in each line
sed 's/(\w+) (\w+)/\2 \1/' input_file.txt
Multi-Line Substitutions
Sed can also perform substitutions that span multiple lines using the newline character \n
in the pattern and replacement strings.
## Replace the first line with the last line
sed '1{/.*/{h;d};$G' input_file.txt
## Reverse the order of lines in a file
sed '1!G;h;$!d' input_file.txt
Conditional Substitutions
Sed supports conditional substitutions, allowing you to apply different replacement patterns based on specific conditions.
## Replace "foo" with "bar" only if the line contains "baz"
sed '/baz/s/foo/bar/g' input_file.txt
## Delete lines that contain both "foo" and "bar"
sed '/foo/!d;/bar/!d' input_file.txt
Extended Regular Expressions
Sed can utilize extended regular expressions (ERE) to perform more complex pattern matching and substitutions.
## Replace all occurrences of "foo", "bar", or "baz" with "replaced"
sed 's/foo\|bar\|baz/replaced/g' input_file.txt
## Extract all email addresses from a file
sed -n '/\w\+@\w\+\.\w\+/p' input_file.txt
By mastering these advanced sed substitution techniques, you can unlock the full potential of text manipulation and streamline your workflows in the Linux/Unix environment.