Searching and replacing text

Searching and replacing text

How to:

Here’s how you wield the power of search and replace in bash:

  1. Swap text within a string using sed:
echo "Hello world" | sed 's/world/universe/'
# Output: Hello universe
  1. Replace text in a file, saving the changes:
sed -i 's/old_text/new_text/g' file.txt
  1. Use variables in your search and replace:
sed "s/$old/$new/g" <<< "I like apple pies"
# Output: I like banana pies

Remember, g at the end means “global”, so you change every match in the line, not just the first one.

Deep Dive

We’ve had tools for text processing on Unix-like systems for ages. sed, short for Stream Editor, is one such tool, and it’s been around since the 1970s. It’s not just for simple replacements; sed can slice and dice text in complex patterns too.

Alternatives? Sure. awk is a bit more advanced and can work wonders with columns and rows. For quick fixes, grep can help you find things, but it won’t replace – it’s more like the lookout.

Under the hood, sed uses regular expressions, which are like wildcards on steroids. They can match almost any pattern you can think of. It makes sed incredibly powerful, but also a bit tricky to master.

See Also