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)

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

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

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com