Find and Replace Strings with Bash
We'll focus on using Bash specifically but also include a fallback plan in case you require a POSIX compliant solution.
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.