How to Replace String in Bash: Simple Syntax and Examples
In bash, you can replace a string using
${variable//search/replace} for simple replacements or use sed for more complex patterns. The ${variable//search/replace} syntax replaces all occurrences of search with replace inside a variable.Syntax
The basic syntax for replacing strings in bash variables is:
${variable//search/replace}: Replaces all occurrences ofsearchwithreplaceinvariable.${variable/search/replace}: Replaces only the first occurrence.sed 's/search/replace/g': Command-line tool for replacing strings in text streams or files, wheresmeans substitute andgmeans global (all occurrences).
bash
${variable//search/replace}
sed 's/search/replace/g' filenameExample
This example shows how to replace all occurrences of apple with orange in a bash variable and how to use sed to replace text in a file.
bash
# Using bash parameter expansion text="I like apple and apple pie." new_text=${text//apple/orange} echo "$new_text" # Using sed to replace in a file (example.txt) # Contents of example.txt: # I like apple and apple pie. sed 's/apple/orange/g' example.txt
Output
I like orange and orange pie.
Common Pitfalls
Common mistakes when replacing strings in bash include:
- Not using double slashes
//to replace all occurrences, which only replaces the first occurrence. - Forgetting to quote variables, which can cause word splitting or globbing issues.
- Using
sedwithout thegflag, which replaces only the first match per line. - Trying to replace strings directly in files without redirecting output or using
-ifor in-place editing.
bash
# Wrong: replaces only first occurrence text="apple apple apple" echo ${text/apple/orange} # Right: replaces all occurrences echo ${text//apple/orange} # Wrong: sed without global flag sed 's/apple/orange/' example.txt # Right: sed with global flag sed 's/apple/orange/g' example.txt
Output
orange apple apple
orange orange orange
Quick Reference
| Command | Description | Example |
|---|---|---|
| ${variable/search/replace} | Replace first occurrence in variable | ${text/apple/orange} |
| ${variable//search/replace} | Replace all occurrences in variable | ${text//apple/orange} |
| sed 's/search/replace/' file | Replace first occurrence per line in file | sed 's/apple/orange/' example.txt |
| sed 's/search/replace/g' file | Replace all occurrences per line in file | sed 's/apple/orange/g' example.txt |
| sed -i 's/search/replace/g' file | Replace all occurrences in file in-place | sed -i 's/apple/orange/g' example.txt |
Key Takeaways
Use ${variable//search/replace} to replace all occurrences of a string in a bash variable.
Use sed with the 'g' flag to replace all occurrences in files or streams.
Always quote variables when replacing strings to avoid unexpected word splitting.
Remember that ${variable/search/replace} replaces only the first occurrence.
Use sed -i for in-place file editing but be cautious as it overwrites the original file.