Difference between revisions of "sed sed"
From Noah.org
Jump to navigationJump to searchLine 2: | Line 2: | ||
== find part of a line, substitute, keep rest of line intact == | == find part of a line, substitute, keep rest of line intact == | ||
− | + | <pre> | |
+ | sed -i -e "s/^#DatabaseDirectory \(.*\)/DatabaseDirectory \\1/" myfile.txt | ||
+ | </pre> | ||
== find pattern in a line, insert new line before it == | == find pattern in a line, insert new line before it == | ||
Line 8: | Line 10: | ||
This finds line that begins with exit(ignore leading spaces), then insert 'authdarmond start' before it. | This finds line that begins with exit(ignore leading spaces), then insert 'authdarmond start' before it. | ||
− | + | <pre> | |
+ | sed -i -e "/^\\s*exit/i authdaemond start" /etc/rc.local | ||
+ | </pre> | ||
== find pattern and append line == | == find pattern and append line == | ||
− | + | This will add qmail-scanner-queue environment variable to qmail-smtpd/run. Notice how the replace pattern spans multiple lines using backslash to escape. | |
− | <pre>sed -i -e | + | <pre> |
− | QMAILQUEUE="/var/qmail/bin/qmail-scanner-queue.pl" ; export QMAILQUEUE | + | sed -i -e "/#\!\/bin\/sh/a\ |
+ | QMAILQUEUE="/var/qmail/bin/qmail-scanner-queue.pl\" ; export QMAILQUEUE" /var/qmail/supervise/qmail-smtpd/run | ||
+ | </pre> | ||
+ | |||
+ | == print everything between two patterns == | ||
+ | |||
+ | Use ranges for this. A range can take a line number or a pattern. | ||
+ | |||
+ | <pre> | ||
+ | sed -n "/begin_pattern/,/end_pattern/p" myfile.txt | ||
</pre> | </pre> | ||
Revision as of 19:45, 23 September 2008
Contents
find part of a line, substitute, keep rest of line intact
sed -i -e "s/^#DatabaseDirectory \(.*\)/DatabaseDirectory \\1/" myfile.txt
find pattern in a line, insert new line before it
This finds line that begins with exit(ignore leading spaces), then insert 'authdarmond start' before it.
sed -i -e "/^\\s*exit/i authdaemond start" /etc/rc.local
find pattern and append line
This will add qmail-scanner-queue environment variable to qmail-smtpd/run. Notice how the replace pattern spans multiple lines using backslash to escape.
sed -i -e "/#\!\/bin\/sh/a\ QMAILQUEUE="/var/qmail/bin/qmail-scanner-queue.pl\" ; export QMAILQUEUE" /var/qmail/supervise/qmail-smtpd/run
print everything between two patterns
Use ranges for this. A range can take a line number or a pattern.
sed -n "/begin_pattern/,/end_pattern/p" myfile.txt
search and replace in multiple files
This will perform a search and replace on all files in a directory tree:
find ./ -type f -exec sed -i -e "s/find_this_text/replace_with_this_text/g" '{}' \;
sed documentation
This is one of the best sed documents I found: Grymoire Sed