Bash - String Manipulation

By xngo on June 17, 2019

Length of string

#!/bin/bash
str="What is the length of this string?"
echo "The length is ${#str}"
# Output:
# The length is 34



Search and Replace string

#!/bin/bash
str="1st dog. 2nd dog. 3r dog"
 
#Replace the 1st occurrence: ${string/find/replace}
str=${str/dog/cat}
echo "${str}"
# Output:
# 1st cat. 2nd dog. 3r dog
 
#Replace all occurrences: ${string//find/replace}
str=${str//dog/cat}
echo "${str}"
# Output:
# 1st cat. 2nd cat. 3r cat
#http://www.arachnoid.com/linux/shell_programming.html

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.