Problem Statement
Explain advanced sed operations including multiple substitutions, line deletion, insertion, and using sed with regular expressions.
Explanation
Sed can perform multiple operations with -e flag or semicolons: sed -e 's/old/new/g' -e 's/foo/bar/g' file.txt applies both substitutions. Or use semicolons: sed 's/old/new/g; s/foo/bar/g' file.txt. For complex operations, use sed scripts: sed -f script.sed file.txt where script.sed contains multiple commands.
Line deletion uses d command: sed '5d' deletes line 5, sed '1,10d' deletes lines 1-10, sed '/pattern/d' deletes lines matching pattern. Insertion uses i command: sed '5i\New line text' inserts before line 5. Append uses a command: sed '5a\New line text' appends after line 5. Replace entire line: sed '5c\Replacement line' replaces line 5.
Regex with sed: sed 's/[0-9]\{3\}-[0-9]\{4\}/XXX-XXXX/g' masks phone numbers. Use capturing groups: sed 's/\([0-9]\{4\}\)-\([0-9]\{2\}\)/\2-\1/' swaps year-month to month-year. Address ranges: sed '/start/,/end/s/old/new/g' substitutes only between markers.
Practical examples: sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config changes SSH port, sed '/^$/d' file.txt removes empty lines, sed 's/^[ \t]*//' file.txt removes leading whitespace. Understand sed addresses (line numbers, patterns, ranges) and commands (s, d, i, a, c) for powerful text manipulation in scripts and automation.
