Difference between revisions of "Sed"

From Secure Computing Wiki
Jump to: navigation, search
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
Great reference: [http://www.grymoire.com/Unix/Sed.html#uh-0 http://www.grymoire.com/Unix/Sed.html#uh-0]
 +
GOLD: [http://sed.sourceforge.net/sed1line.txt sed 1-liners]
 
* Find '''foo''' and replace it with '''bar''' on the first line only, edit in place:
 
* Find '''foo''' and replace it with '''bar''' on the first line only, edit in place:
 
<pre>sed -i "" "1 s/foo/bar/" <filename></pre>
 
<pre>sed -i "" "1 s/foo/bar/" <filename></pre>
Line 5: Line 7:
 
<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>
 +
 
 +
* Replace all instances of '''foo''' with '''bar''' on lines containing '''baz''' within file <filename>.
 +
<pre>sed -e '/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" -n "s/foo/bar/g <filename></pre>
+
<pre>sed -i '.bak' 's/foo/bar/g' <filename></pre>

Latest revision as of 18:19, 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>
  • Replace all instances of foo with bar on lines containing baz within file <filename>.
sed -e '/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>