Variable Substitution in Bash [Replace Character & Substring]

Bash programmers do the replacement, the substitution, and the removal of the bash variable too often. It helps them print necessary text on the terminal, customize a command with the necessary option to get their necessary output, replace unnecessary words from a text, concatenate two or more variables and print, and do arithmetic operations. In this article, I will demonstrate to you these types of tasks which will help you to get a holistic idea of this topic.

Syntax to Substitute, Replace, Remove Variable and Substring

  1. To substitute the Bash variable:
    echo "String, $variable_name!"
  2. To replace substring from string:
    new_string="${original/old_substring/new_substring}"
  3. To remove a substring from a variable:
    result="${original_string/$substring_to_remove/}"

Variable Substitution in Bash

Bash variable substitution is a process where the value of a variable substitutes or replaces another variable. The $(..) syntax is commonly used for variable substitution. I have listed some examples related to this topic below. The examples are simple variable substitution, concatenation of string using variable substitution, arithmetic substitution using arithmetic expansion, and command substitution by creating customized commands.

Example 01: Bash Variable Substitution

Here, I will create a Bash script to print a text with a substituted variable value.

To print a text with the variable substitution, use the following script:

!#/bin/bash

#assigning the value of the name variable
name="John"

#substituting name variable
echo "Hello, $name!"
EXPLANATION

#!/bin/bash, is called shebang or hashbang. It indicates the interpreter to be used for executing the script, in this case, it’s bash. After that, the name="John" command has assigned a value to the name variable. Finally, the echo "Hello, $name!" command has printed a text on the terminal using the echo command where the name variable is replaced by the assigned value.

I have a bash script which has printed a text where variable name is substituted by its value.The image shows that the bash script has printed a text on the terminal where the name variable is substituted by its assigned value.

Example 02: Concatenation of String Utilizing Variable Substitution

Here, I will develop a bash script that will concatenate two variables utilizing variable substitution.

To concatenate string using variable substitution, use the following script:

#/bin/bash

#assigning first_name and last_name variable
first_name="John"
last_name="Doe"

#concatenating two variables utilizing variable substitution
full_name="$first_name $last_name"

#printing the concatenated result
echo "Full Name: $full_name"
EXPLANATION

The first_name="John" and last_name="Doe" commands have assigned value to the first_name and last_name variables. After that, the full_name="$first_name $last_name" command has concatenated the value of the first_name and the last_name variables and kept it on the full_name variable. Finally, the echo "Full Name: $full_name" command has printed the value on the terminal.

I have developed a bash script which has concatenated two names and printed it on the terminal.The Bash script has concatenated two variables using variable substitution and printed on the terminal. Here John and Doe from the output line come from the first_name and the last_name variable respectively. After concatenation, I got Jogn Doe on the terminal.

Example 03: Arithmetic Substitution Using Arithmetic Expansion

In this example, I will develop a bash script that will do a mathematical addition utilizing the arithmetic substitution.

To do arithmetic substitution using arithmetic expansion, follow the script provided below:

#!/bin/bash

#assigning value to the num1 and the num2 variable
num1=5
num2=3

#arithmetic Substitution
result=$((num1 + num2))

#printing the result
echo "Sum of $num1 and $num2:$result"
EXPLANATION

The num1=5 and num2=3 commands have assigned value to the num1 and the num2 variables. After that, the result=$((num1 + num2)) command has calculated the summation of the num1 and the num2 variables with the help of arithmetic substitution. Finally, the echo "Sum $num1 and $num2:$result" command has printed the result on the terminal.

Here the bash script has used arithmetic substitution to sum the num1 and the num2 variable.The bash script has calculated the summation of the num1 and the num2 variables utilizing the arithmetic substitution method.

Example 04: Command Substitution by Creating Customized Command

Here, I will create a customized command and then print the output of the customized command on the terminal.

To create a customized command and print its output, use the following script:

#!/bin/bash

#creating a customized date
current_date=$(date +%Y-%m-%d)

#printing the output of the customized command
echo "Current Date: $current_date"
EXPLANATION

The current_date=$(date +%Y-%m-%d) command has created a customized date where Y specifies year, m specifies month and the d specifies day. Then the echo "Current Date: $current_date" command prints the output of the customized command.

In this bash script, a customized date command has been created then this customized command has printed the output on the terminal.The bash script has created a customized date command and printed the output of that command on the terminal.

Replacing Substring in a Variable

Bash variable replacement is a process where the value of a variable replaces or variable. I have listed some examples related to this topic below.

Example 01: Replace a Single Occurrence Using Single Slash (/) Operator

In this example, I will develop a bash script that will look for a match of a specific substring for a single time and will replace it with another substring.

To replace a specific substring with another substring using a single slash (/) operator, follow the below script:

#!/bin/bash

#original variable is assigned
original="Hello, World!"

#”World” will be replaced by “Everyone” from the original variable and kept on the new_string
new_string="${original/World/Everyone}"

#new_string will be printed
echo "$new_string"
EXPLANATION

The original="Hello, World!" command has assigned a value to the original variable. After that, the new_string="${original/World/Everyone}" command has replaced the “World” with the “Everyone”. Finally, the echo "$new_string" command printed the new_string variable value on the terminal.

This bash script has replaced the “World” with “Everyone” from the original string and keep it to a new string then printed the updated new string on the terminal.The image shows that the bash script has replaced the “World” with “Everyone” and printed the updated string on the terminal.

Example 02: Replace All Occurrences Using Double Slash (//) Operator

Following the previous method, I will develop another bash script in a different way that will look for a match of a specific substring and replace it with another substring. This is just another approach to using a single slash(/).

To replace a specific substring with another substring using the double slash (//) operator, follow the below script:

#!/bin/bash

#string assigning
original="She sells seashells by the seashore. She shells seashells for sure."

#sh will be replaced by SH
new_string="${original//sh/SH}"

#printing the result
echo "$new_string"
EXPLANATION

The original="She sells seashells by the seashore. She shells seashells for sure." command has assigned a string to the original variable. After that the new_string="${original//sh/SH}" command has replaced all “sh” with “SH” and kept it on the new_string. Finally, the echo "$new_string" command has printed the value of the new_string variable on the terminal.

This Bash script has replaced the character “SH” with the character “sh” and keep it to a new_string then printed the new_string on the terminal.The image shows that the Bash script has replaced the character “SH” with the character “sh” and printed the new_string on the terminal.

Example 03: Replace One Character with Another Using tr Command

One might use one character in place of another character. In such a situation, the programmer can replace one character with another using the tr command. To know more, follow the below script.

To replace one character with another using the tr command, follow the script provided below:

#!/bin/bash

#assigning main string
Main_string="Linux Simply"

#replacing n by p and save it to New_string
export New_string=$(echo "$Main_string" | tr 'n' 'p')

#printing the value of Main_string
echo "Main_string:" $Main_string

#printing the value of Modified_string
echo "Modified_string:" $New_string
EXPLANATION

The Main_string="Linux Simply" command has assigned value to Main_string. After that the export New_string=$(echo "$Main_string" | tr 'n' 'p') command has replaced ‘n’ with ‘p’ with the help of the tr command and the export command. Then the echo "Main_string:" $Main_string command prints the value of the Main_string. Finally, the echo "Modified_string:" $New_string command has printed the value of the New_string.

This Bash script has replaced the 'n' with the 'p' utilizing the tr command.The image shows that the Bash script has replaced the n character with the p character with the help of the tr command.

An alternative to using the tr command is parameter expansion. The syntax for parameter expansion is:

New_string="${Main_string//(replaced character)/(new character)}"

Removing Substring from a Variable

Bash variable removal is a process where some words or sub-strings from the main string is deleted. I have listed some examples related to this topic below.

Example 01: Remove a Specific Substring From a Given String by Using Single Slash (/) Operator

In this example, I will develop a Bash script that will remove a substring from a sentence utilizing the single slash(/).

To remove a specific substring from a given string, use the following code:

#!/bin/bash

# Original sentence
sentence="Hello, world! This is an example."

# Substring to remove
substring="world"

# Remove substring using parameter expansion
result="${sentence/$substring/}"

# Print the result
echo "Original Sentence: $sentence"
echo "Substring to Remove: $substring"
echo "Result after removal: $result"
EXPLANATION

The sentence="Hello, world! This is an example." and substring="world" commands have assigned strings to the sentence and the substring variables. After that, the result="${sentence/$substring/}" command has removed the substring from the sentence utilizing the single slash(/). Finally, the echo "Original Sentence: $sentence", echo "Substring to Remove: $substring", and echo "Result after removal: $result" commands have printed the Original sentence, the substring, and the result on the terminal.

Here I have developed a Bash script that has replaced a sub-string from the main string by utilizing the single slash(/) and kept it to a new string then printed the new string on the terminal.The Bash script has replaced the sub-string from the main string by utilizing the single slash(/) and printed the new string.

Example 02: Using Double Slash(//) Operator to Remove a Specific Substring from a Given String

Here, I will develop a Bash script that will remove a substring from a sentence utilizing the double slash(//). This is an alternative approach of the single slash(/) approach.

To remove a specific substring from a given string, follow the below script:

#!/bin/bash

#original and substring_to_remove string assigned
original_string="Hello, world!"
substring_to_remove="world"

#sub-string will be removed from the original string and kept on the result
result="${original_string//$substring_to_remove/}"

#result will be printed
echo "$result"
EXPLANATION

The original_string="Hello, world!" and the substring_to_remove="world" commands have assigned value to the original_string variable and the substring_to_remove variable. After that, the result="${original_string//$substring_to_remove/}" command has removed a the substring_to_remove from the original_string utilizing the double slash(//). Finally, the echo "$result" command has printed the result on the terminal.

Here the Bash script has replaced the sub-string from the main string utilizing the double slash(//) and kept it to a new string then printed the new string on the terminal.The Bash script has replaced the sub-string from the main string with the utilizing the double slash(//) and printed the new string.

Example 03: Remove Substring by Using sed (Stream Editor) Command

Here, I will develop a Bash script that will remove a substring from a original string utilizing the sed command.

To remove a substring using the sed command, follow the below script.

#!/bin/bash

#value assigning
original_string="Hello, world!"
substring_to_remove="world"

#removing substring_to_remove from original_string using sed command
result=$(echo "$original_string" | sed "s/$substring_to_remove//g")

#printing the result on the terminal
echo "$result"
EXPLANATION

The original_string="Hello, world!" and the substring_to_remove="world" command have assigned value to the original_string and the substring_to_remove variable. After that, the result=$(echo "$original_string" | sed "s/$substring_to_remove//g") command has removed the substring_to_remove from the original_string utilizing the sed command. Finally, the echo "$result" command has printed the result on the terminal.

Here this Bash script has removed 'world' from the main string utilizing the sed command and printed the new string Hello on the command line.The Bash script has removed the sub-string “world” from the main string with the help of the sed command and printed the new string Hello on the command line.

Example 04: Removing of a Substring by Using the awk Command

In this example, I will develop a Bash script that will remove a substring from an original string utilizing the awk command.

To remove the substring by using awk command, follow the below script:

#!/bin/bash

# Remove "world" from the variable
original_string="Hello, world!"
substring_to_remove="world"

#removing substring_to_remove from original_string using awk command
result=$(echo "$original_string" | awk -v var="$substring_to_remove" '{gsub(var,"")}1')

#printing the result on the terminal
echo "$result"
EXPLANATION

The original_string="Hello, world!" and the substring_to_remove="world" command have assigned value to the original_string and the substring_to_remove variable. After that, the result=$(echo "$original_string" | awk -v var="$substring_to_remove" '{gsub(var,"")}1') command has piped the output of echo command to awk command which removed the substring_to_remove from the original_string. Finally, the echo "$result" command has printed the result on the terminal.

The Bash script has removed 'world' from the main string utilizing the awk command and printed the new string on the terminal.The Bash script has removed the sub-string from the main string with the help of the awk command and printed the new string.

Conclusion

In this article, I have tried to explore the full process of bash variable substitution and replace characters. I believe, after going through this article, you will be productive enough to remove or a sub-string from the main string, customize a command, or replace a variable by its value.

People Also Ask

Which expression is used in bash for command substitution?

The $(..) syntax is the basic syntax for command substitution where the command to be executed is enclosed between the parentheses. This form is the recommended syntax of command substitution.

Can you use substitution with 3 variables?

Yes, you can use substitution with 3 variables. Concatenating strings from 3 variables which is the basic demonstration of the usage of variable substitution with three variables.

Are bash variables case-sensitive?

Yes, bash variables are case-sensitive. Variables in Bash Scripts are untyped and declared on the definition. Bash also supports some basic type declaration using the declare option, and bash variables are case-sensitive.

Can Bash variables have numbers?

Yes, Bash variables can have numbers. A variable in Bash can contain a number, a character, or a string of characters. Variable names can contain uppercase, and lowercase letters, numbers, underscores, and digits.

How do I replace a character in a variable in bash?

The basic syntax for replacing any character in a variable in bash is:

${original/substring_to_replaced/new_substring}

Here, the original is the main string, substring_to_replaced is the substring to be replaced, and finally the new_substring is the new substring which will be in place of substring_to_replaced.

Related Articles


<< Go Back to Using Variables in Bash Scripting | Bash Variables | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment