0
0
Bash Scriptingscripting~5 mins

String replacement (${var/old/new}) in Bash Scripting

Choose your learning style9 modes available
Introduction
You use string replacement to change parts of text stored in a variable quickly without extra tools.
Fix a typo in a word inside a variable.
Change a file extension in a filename stored in a variable.
Replace a word in a sentence stored in a variable.
Update a URL or path stored in a variable.
Modify a configuration value inside a string.
Syntax
Bash Scripting
${variable/old/new}
This replaces the first occurrence of 'old' with 'new' in the variable's value.
To replace all occurrences, use ${variable//old/new} with double slashes.
Examples
Replaces 'world' with 'universe' in the variable 'text'.
Bash Scripting
text="hello world"
echo "${text/world/universe}"
Changes the file extension from 'txt' to 'pdf'.
Bash Scripting
filename="report.txt"
echo "${filename/txt/pdf}"
Replaces only the first 'fish' with 'cat'.
Bash Scripting
sentence="one fish two fish"
echo "${sentence/fish/cat}"
Replaces all 'fish' with 'cat' using double slashes.
Bash Scripting
sentence="one fish two fish"
echo "${sentence//fish/cat}"
Sample Program
This script shows how to replace the first and all occurrences of 'apples' with 'oranges' in a string variable.
Bash Scripting
#!/bin/bash
text="I love apples and apples are tasty"
# Replace first 'apples' with 'oranges'
new_text="${text/apples/oranges}"
echo "$new_text"
# Replace all 'apples' with 'oranges'
all_replaced="${text//apples/oranges}"
echo "$all_replaced"
OutputSuccess
Important Notes
String replacement does not change the original variable unless you assign it back.
It works only on variables, not on command output directly.
Use double slashes (//) to replace all matches, single slash (/) for the first match only.
Summary
Use ${var/old/new} to replace the first match of 'old' with 'new' in a variable.
Use ${var//old/new} to replace all matches.
This is a quick way to edit text inside variables without extra commands.