Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Find and Replace Strings with Bash

find-and-replace-strings-with-bash.jpg

We'll focus on using Bash specifically but also include a fallback plan in case you require a POSIX compliant solution.

Quick Jump:

String replacement is something I often do in scripts.

Like most other programming languages, Bash has a way to do this without too much fuss.

Replace only the first occurrence:
state="on on on"

state="${state/on/off}"

echo "${state}"
# off on on
Replace all occurrences:
state="on on on"

# The only difference is we're using // instead of / for the first separator
state="${state//on/off}"

echo "${state}"
# off off off

Both methods take advantage of parameter expansion which is a feature of Bash.

If you want a POSIX compliant solution you can reach for using sed:
state="on on on"

# Replace only the first occurrence
state="$(echo "${state}" | sed "s/on/off/")"
echo "${state}" # off on on

# Replace all occurrences with the "g" (global) option
state="$(echo "${state}" | sed "s/on/off/g")"
echo "${state}" # off off off

This could be useful if you’re running your script in a container that might only have access to sh or another shell which isn’t compatible with bash.

The video below shows using all of the methods covered above.

# Demo Video

Timestamps

  • 0:16 – Doing it with Bash
  • 1:26 – Using sed to be POSIX compliant

What was the last string you replaced in a script? Let me know below.

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per year (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments