Explaining Find and Replace with Forward Slashes in Bash

The aim of this page📝 is to explain find&replace syntax in bash (via parameter expansion; not with sed)

Pavol Kutaj
2 min readDec 5, 2022

Historically, bash has adopted the following constructs from Kornshell, named after David Korn (computer scientist) — Wikipedia, developed in Bell Labs in 1983. For fun, read the self-inflammatory KornShell Overview, you have to have some ego to write this description of your product and name it after your little funny self. Of course, KornShell was a commercial product (which is why we don’t use it in Linux). For simple shell, genealogy see also The History of Computing: The Evolution Of Unix, Mac, and Chrome OS Shells

1. The syntax utilizing forward slashes for find and replace is at first highly confusing

  • I am just picking up bash and I am learning also by reading and transcribing
  • This was one of the first instances of encountering find&replace and I had no idea whatsoever what it may be about
WORKSPACE="${OLD_SCHOOL_JOB//./_}"
WORKSPACE="${WORKSPACE/-/_}"
  • I may have easily just skipped those lines.
  • Let’s look at the syntax now
<!-- BASH SYNTAX FOR FIND AND REPLACE-->
<cmd> ${<variable>/<find>/<replace_first>}
<cmd> ${<variable>//<find>/<replace_all>}
  • Find and replace occurs with ${} block (parameter expansion)
  • If curious, see Shell parameter and variable expansion
  • First comes a variable containing the data you want to replace
  • Second comes a glob pattern for find
  • Third comes the value for replace
  • The double // replaces all
  • The single / replaces a single/first occurrence of the match

2. Let’s exemplify by replacing all colons in $PATH built-in variable with a new line

<!-- EXAMPLE -->
echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin

echo "${PATH//:/$'\n'}"
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin

3. Uncle Bob says that code if full of optical illusions and, unfortunately, this is one of them

4. In comparison, Powershell is a pleasure to work with

  • In Powershell, you get this with -replace operator with a following readable syntax
<!-- POWERSHELL SYNTAX -->
<input> -replace <regular-expression>, <substitute>

5. And of course, for Find and Replace within a file, you use a sed command

  • sed stands for stream editor and is traditionally used for F&R within files
The easiest way is to use sed (or perl):
sed -i -e 's/abc/XYZ/g' /tmp/file.txt

Find and Replace Inside a Text File from a Bash Command — Stack Overflow

7. LINKS

--

--

Responses (1)