From Wiki

Revision as of 17:23, 19 February 2010 by Admin (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)
Jump to: navigation, search


SED - Stream Editor: Edit files via bash

Example of replacing text

sed -i "s/wordtoreplace/wordtoreplacewith/" /path/to/file/file.txt

# -i = Edit File in place
# s/ = s/regexp/replacement/ (search regexp and replace)

Replace all instances of text in a line

echo "teztz" | sed "s/z/-/"

The above sed will *NOT* replace ALL instances of z with -. The following instead is required:

echo "teztz" | sed "s/z/-/g"
#The /g is required to replace all instances.

Replace a Forward Slash (/) using sed

The following situation: A script outputs the following:


Using Munin_Statistics, I want to be able to graph disk usage. The above string cannot be used to create a file for disk usage. I want to replace all instances of / with -.

du -B 1 --max-depth=1 /home | sed "s/\//-/g"

The trick is to escape the / with a \.

Replace urls in files

find . -type f -iname "*.php" -exec sed -i "s|||" {} \;
#the pipe | is used to delimit sed

Delete text in files

sed -i "/wordtodelete/d" text.txt
#the /d is for delete instead of replace.

Other information about sed

man sed
Personal tools