Difference between revisions of "Sed"

From wiki
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
Check the [https://unix.antiperfect.org/scripting/sed/ APO unix pages] for more.
 
Check the [https://unix.antiperfect.org/scripting/sed/ APO unix pages] for more.
 +
 +
;NOTE!! On some systems you need the -E option to have possix [[Regular Expressions]] supported
  
 
=Tricks=
 
=Tricks=
  
 
;<code>sed 's/\r//' filename > newfilename</code>
 
;<code>sed 's/\r//' filename > newfilename</code>
:dos2unix substitute, remove all dos line endings.
+
:dos2unix substitute, remove all DOS line endings.
  
 
;<code>sed -i 'commands' filename</code>
 
;<code>sed -i 'commands' filename</code>
:Edit the file directly (inplace) by default the result is sent to standard output
+
:Edit the file directly (inplace), by default the result is sent to standard output.
  
 
=Basics=
 
=Basics=
Line 16: Line 18:
  
 
;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. Use \n to insert a newline.
  
 
;sed 's/pattern(with)sub(patterns)/\1 newpartofstring \2/' <file>
 
;sed 's/pattern(with)sub(patterns)/\1 newpartofstring \2/' <file>

Latest revision as of 09:44, 21 March 2023

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.