Sed

From wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Check the APO unix pages for more.

NOTE!! On some systems you need the -E option to have possix Regular Expressions supported

Tricks

sed 's/\r//' filename > newfilename
dos2unix substitute, remove all DOS line endings.
sed -i 'commands' filename
Edit the file directly (inplace), by default the result is sent to standard output.

Basics

sed '/<pattern>/<action>' <file>
Execute action on all lines in <file> matching <pattern>
Simple actions are d(elete) (can be negated using !d, delete all lines not matching), p(rint), q(uit)
sed 's/<old_string>/<new_string>/g' <file>
Substitute, no whitespace is allowed after the command (s), the first character following s is the fieldseperator./g substitutes all matching patterns in a line. Use \n to insert a newline.
sed 's/pattern(with)sub(patterns)/\1 newpartofstring \2/' <file>
\1 and \2 refer to the subpatterns between brackets ().
sed '/<pattern>/[ia]<text>'
i inserts <text> before the matched line, a after the line
sed '/<pattern>/[rw] <file>'
r(ead) from or w(rite) to <file> if <pattern> is matched.