Practical Sed Strategies for Line Manipulation
Removing Lines Adjacent to Patterns
To remove the line immediately preceding and following a specific pattern, combine address ranges with flow control commands.
sed -i -e '/ERROR/{n;d}' -e '$!N;/\n.*ERROR/!P;D' system.log
Deleting the Preceding Line
When only the line before a match is required to be removed, utilize the hold space logic to buffer lines.
sed -i -e '$!N;/\n.*ERROR/!P;D' system.log
Deleting the Subsequent Line
Removing the line immediately after a match is straightforward using the next command.
sed -i '/ERROR/{n;d}' system.log
Utilizing Shell Variables
Dynamic patterns can be passed into sed using shell variable expansion. Ensure proper quoting to handle special characters.
SEARCH_TERM="CRITICAL"
sed -i -e '/'"$SEARCH_TERM"'$/{n;d}' -e '$!N;/\n.*'"$SEARCH_TERM"'$/!P;D' audit.log
Inserting Text Around Matches
The i and a commands allow insertion before or after a matched line, respectively. Escape sequences are often required for newlines.
Inserting Before a Match
To add a configuration directive before a specific domain entry:
sed -i '/deny untrusted.net/i\allow trusted_partner.org' access.conf
Inserting After a Match
To append a rule immediately following a domain restriction:
sed -i '/deny untrusted.net/a\allow trusted_partner.org' access.conf
Adding Configuration Directives
Specific server settings can be injected relative to existing parameters.
sed -i '/port/a\ port 443;' server.cfg
Multi-line Insertion
Complex blocks, such as cron jobs or multiple config lines, can be inserted using escaped newline characters (\n).
sed -i '/backup_script.sh/a\# Maintenance Window\n*/10 * * * * /usr/bin/php /var/www/cron/cleanup.php\n*/10 * * * * /usr/bin/php /var/www/cron/report.php' crontab.txt
Inserting Before Specific Parameters
Similar to appending, insertion before a parameter uses the i flag.
sed -i '/port/i\ port 443;' server.cfg
Advanced Deletion Scenarios
Removing the Previous Line via Loop
An alternative method for deleting the line prior to a match involves labeling and branching.
sed -i -e :a -e '$!N;s/.*\n\(.*port 443\)/\1/;ta' -e 'P;D' server.cfg
Deleting Range Blocks
Content between two specific markers can be removed entire.
sed -i '/<VirtualHost>/,/<\/VirtualHost>/d' $config_file
Deleting Match and Following Lines
To remove a matching line plus a fixed number of subsequent lines, use the offset syntax.
sed -i '/TempStorage/,+2d' cache.txt
Configuration Replacement
Common tasks involve toggling comments or changing socket paths in web server configurations.
sed -i 's/#php_handler/php_handler/g;s/php_handler unix:\/var\/run\/php.sock/#php_handler/' nginx.conf