Get started with sed

[Zheng Qu] | Jun 26, 2020 min read

What is sed?

sed is a “stream editor for filtering and transforming text”. Here is a very detailed tutorial.

Basic usages

Use “s” for substitution

Basic syntax:

echo "Sunday Monday" | sed 's/day/night/'
Sunnight Monday

Note that only the first occurrence of day was replaced by night. To replace all, you have to use sed pattern flag /g for global replacement.

echo "Sunday Monday" | sed 's/day/night/g'
Sunnight Monnight

Flexible delimiters

I think we all agree that the following code is ugly:

echo "/usr/local/bin/n" | sed 's/\/usr\/local/\/usr/'

With sed, the delimiter does not need to be /. It can be /, _, -, #, * etc. Pick the one fit you the best.

echo "/usr/local/bin/n" | sed 's_/usr/local_/usr_'
echo "/usr/local/bin/n" | sed 's-/usr/local-/usr-'
echo "/usr/local/bin/n" | sed 's#/usr/local#/usr#'
echo "/usr/local/bin/n" | sed 's*/usr/local*/usr*'
echo "/usr/local/bin/n" | sed 's</usr/local</usr<'
# ...
comments powered by Disqus