Difference between revisions of "Sed"

From Secure Computing Wiki
Jump to: navigation, search
Line 10: Line 10:
 
* 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 -i -e 's/foo/bar/' <filename></pre>
 
<pre>sed -i -e 's/foo/bar/' <filename></pre>
 +
 +
* Find ALL instances of '''foo''' and replace with '''bar''' only on lines containing '''baz''' within a file <filename>.
 +
<pre>sed -e 's/baz/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' 's/foo/bar/g' <filename></pre>
 
<pre>sed -i '.bak' 's/foo/bar/g' <filename></pre>

Revision as of 17:18, 31 March 2009

Great reference: http://www.grymoire.com/Unix/Sed.html#uh-0 GOLD: sed 1-liners

  • 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 instances of foo and replace with bar only on lines containing baz within a file <filename>.
sed -e 's/baz/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>