Difference between revisions of "Sed"

From wiki
Jump to: navigation, search
(Tricks)
(Basics)
 
Line 10: Line 10:
  
 
=Basics=
 
=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>
 
;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.
 
: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.
Line 16: Line 21:
 
:\1 and \2 refer to the subpatterns between brackets ().
 
:\1 and \2 refer to the subpatterns between brackets ().
  
;sed '/<pattern>/d'
+
;sed '/<pattern>/[ia]<text>'
:Delete matching line. !d negates the match => delete all lines not matching.
+
: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.

Latest revision as of 11:45, 6 November 2019

Check the APO unix pages for more.

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.
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.