Difference between revisions of "Sed"

From Secure Computing Wiki
Jump to: navigation, search
Line 5: Line 5:
 
<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>
 
<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.''
 
<pre>sed -i "" "s/foo/bar/;q" <filename></pre>
 
  
 
* Find ALL instances of '''foo''' and replace it with '''bar''' within a file <filename>.
 
* Find ALL instances of '''foo''' and replace it with '''bar''' within a file <filename>.
<pre>sed -in "s/foo/bar/g" <filename></pre>
+
<pre>sed -i -e 's/foo/bar/' <filename></pre>
  
 
* Find ALL instance of '''foo''' and replace it with '''bar''' within a file <filename>, and create a backup of the original file.
 
* Find ALL instance of '''foo''' and replace it with '''bar''' within a file <filename>, and create a backup of the original file.
<pre>sed -i ".bak" -n "s/foo/bar/g <filename></pre>
+
<pre>sed -i '.bak' 's/foo/bar/g' <filename></pre>

Revision as of 12:57, 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 ALL instances of foo and replace it with bar within a file <filename>.
sed -i -e 's/foo/bar/' <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' 's/foo/bar/g' <filename>