bash replace in string code example
Example 1: bash replace substring
echo [string] | sed "s/[original]/[target]/g"
Example 2: bash script: replace . with :
#To replace the first occurrence of a pattern with a given string,
#use ${parameter/pattern/string}:
#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/$secondString}"
# prints 'I love Sara and Marry'
#To replace all occurrences, use ${parameter//pattern/string}:
message='The secret code is 12345'
echo "${message//[0-9]/X}"
# prints 'The secret code is XXXXX'
#(This is documented in the Bash Reference Manual, §3.5.3 "Shell Parameter Expansion".)
Example 3: bash replace beginning of string
$ cat shortest.sh
#! /bin/bash
filename="bash.string.txt"
echo ${filename#*.}
echo ${filename%.*}
$ ./shortest.sh
After deletion of shortest match from front: string.txt
After deletion of shortest match from back: bash.string
Example 4: bash search and replace text in file
# Basic syntax using awk:
awk '{gsub(regex, substitution_text, $field#); print $0;}' input_file
# Where:
# - gsub is a function that replaces every regular expression (regex)
# match with substitution_text.
# - $field# is optional but can be used to specify a particular field
# where gsub should operate. (This is useful if you want to
# restrict the substitutions to a specific column)
# Example usage:
awk '{gsub(" ","",$0); print $0;}' input_file
# This replaces every space " " with nothing "", thereby eliminating all
# whitespace from the file