Difference between revisions of "Sed"

From Secure Computing Wiki
Jump to: navigation, search
Line 4: Line 4:
 
* Find all lines containing '''foo''' and remove those lines from file <filename>:
 
* Find all lines containing '''foo''' and remove those lines from file <filename>:
 
<pre>sed -i '' -e 's/^.*foo.*//' -e '/^$/d' <filename></pre>
 
<pre>sed -i '' -e 's/^.*foo.*//' -e '/^$/d' <filename></pre>
 +
<pre>sed -i -e '/foo/d' <filename></pre>
  
 
* Find the first instance of '''foo''' and replace it with '''bar''' within a file <filename>.  ''This is really good for multi-gigabyte files where you want to change something on the first line without loading the file into an editor.''
 
* Find the first instance of '''foo''' and replace it with '''bar''' within a file <filename>.  ''This is really good for multi-gigabyte files where you want to change something on the first line without loading the file into an editor.''

Revision as of 12:54, 13 February 2008

  • Find foo and replace it with bar on the first line only, edit in place:
sed -i "" "1 s/foo/bar/" <filename>
  • Find all lines containing foo and remove those lines from file <filename>:
sed -i '' -e 's/^.*foo.*//' -e '/^$/d' <filename>
sed -i -e '/foo/d' <filename>
  • Find the first instance of foo and replace it with bar within a file <filename>. This is really good for multi-gigabyte files where you want to change something on the first line without loading the file into an editor.
sed -i "" "s/foo/bar/;q" <filename>
  • Find ALL instances of foo and replace it with bar within a file <filename>.
sed -in "s/foo/bar/g" <filename>
  • Find ALL instance of foo and replace it with bar within a file <filename>, and create a backup of the original file.
sed -i ".bak" -n "s/foo/bar/g <filename>