Building Bash Muscle (9)

Let’s replace a text with some other text. I’m going to replace ‘hello’ in ‘hello world’ with ‘hi’. The result will be ‘hi world’. I’m going to have ‘hello world’ in a variable.

var1='hello world'
echo $var1

The following code replaces hello with hi and print the result out in the terminal.

echo ${var1//hello/hi}

You can alternatively use regular expression.

var2='food moon red green monster'
echo ${var2//?oo?/whatever}

The result looks like the following.

whatever whatever red green monster

To recap, the syntax is ${variable//replacefrom/replaceto}

Author: admin

A software engineer in greater Seattle area

Leave a Reply

Your email address will not be published. Required fields are marked *