sed
Sed is a string editor program. It can manipulate data using regular expressions.
The basic syntax for sed is sed SCRIPT INPUTFILE
where a SCRIPT is the format used to replace or modify.
If you want to pass options, then the format is sed OPTIONS SCRIPT INPUTFILE
Here is a simple example that removes spaces from a string:
echo foo bar | sed 's/\ //' # returns foobar
In the script, characters that would be parsed by the shell need to be escaped.
Basic syntax
Here are some of the common arguments that will be used.
First of all, if you are passing arguments, and not just a script, then you need to specify which argument is the script. The same example as before, using -e
or –expression
would look like this:
echo foo bar | sed -e 's/\ //' # returns foobar
Scripting from a file
You can load a script from a file instead of passing it as an expression. The syntax is the same, you still need to escape characters.
echo 's/\ //' > /tmp/rules.txt echo foo bar | sed -f /tmp/rules.txt
Edit a file
You can have sed update the file directly:
echo foo bar > /tmp/foobar.txt sed -e 's/\ //' /tmp/foobar.txt -i
BSD / Darwin: BSD's version of sed will use an extension given to -i
to create a backup file of the original. So sed -i .bar foo
will create foo.bar
while updating foo
as well. By comparison, GNU sed accepts an optional argument if given directly after the option: sed -i.bar
.
To workaround the inconsistency, you have two options. Pass an empty character after the option for both:
sed -i'' ...
Or, pass -i
as the last option:
sed ... -i
Regular expressions
If you need to use regular expressions in the same format that egrep does, use -r
as well.
Global replacement
By default, sed will only replace the first occurrence of a match. With a regexp modifier, you can have it do more.
Use g
to replace all instances:
echo foo bar | sed 's/o//' #returns fo bar echo foo bar | sed 's/o//g' #returns f bar