sed
eharetea

A brief, yet in depth overview of the string replacing capabilities of the sed command. sed Unix Matrix

String replacing with sed.

Date Created:Friday December 29th, 2006 03:41 AM
Date Modified:Wednesday July 30th, 2008 11:20 PM

SED 


LINE SPACING
*double space the file
sed G noisey.vfl
*triple space
sed 'G;G' noisey.vfl

BEFORE AND AFTER LINE SPACING
*insert a blank line below every line that matches normalize
sed '/normalize/{G;}' noisey.vfl
sed '/normalize/G' noisey.vfl
*insert a blank line above every line that matches normalize
sed '/normalize/{x;p;x;}' noisey.vfl
*insert a blank line above and below every line which matches normalize
sed '/normalize/{x;p;x;G;}' noisey.vfl


REPLACE WITH SED
*standard replace
sed 's/foo/bar/g' filename
*faster replace (you are telling it the search string first
sed '/foo/ s/foo/bar/g' filename
*shorthand
sed '.foo/ s//bar/g' filename

*\t is tab, thus this would replace rough with 3 tabs
sed 's/rough/\t\t\t/g' noisey.vfl


SELECTIVE REPLACING
*replace "ray" with "no" on lines that have raytrace
sed '/raytrace/s/ray/no/g' test.ifd
*replace "ray" with "no" on all lines that don't have raytrace 
sed '/raytrace/!s/ray/no/g' test.ifd

*replace first instance of 0 to good in a line
sed 's/0/good/' test.ifd
*replace 7th instance of 0 to good in a line
sed 's/0/good/7' test.ifd
*replace all instances of 0 to good in a line
sed 's/0/good/g' test.ifd


PRINT LINE NUMBER 7
sed -n '7p' noisey.vfl
*same as above but more efficient on larger files
sed '7p;d' noisey.vfl

PRINT LINES THAT MATCH EXPRESSION
sed '/raytrace/!d' test.ifd
sed -n '/raytrace/p' test.ifd


ALIGN
*gets rid of all leading whitespace in front of each line
sed 's/^[ \t]*//' noisey.vfl
*gets rid of all trailing whitespace at end of each line
sed 's/[ \t]*$//' noisey.vfl
*delete BOTH leading and trailing whitespace from each line
sed 's/^[ \t]*//;s/[ \t]*$//' noisey.vfl
put a space, the word houdini, and a space in the begining of every line
sed 's/^/ houdini /' noisey.vfl
*tab every line
sed 's/^/\t/' noisey.vfl


CUSTOM DELIMETER
you can choose a character for a delimeter in regexp's, like @ or !

cat test.ifd |sed -e 's/houdini/placer/g' -e 's/halo/render/g'
cat test.ifd |sed -e 's@houdini/3d/houdini/00__content@placer@g'
cat test.ifd |sed -e 's@/home/houdini/3d/houdini/00__content@placer@g' | mantra

sed 's!home/houdini/3d/houdini/00__content!!g' test.ifd | mantra -Q r