Wednesday, February 17, 2021

Bash: String manipulation

For this example string: 
my_string="example.string.with.dots"
%: Remove match from last occurrence
echo "${my_string%.*}" # --> example.string.with
%%: Remove match from first occurrence
echo "${my_string%%.*}" # --> example
#: Remove match until first occurrence
echo "${my_string#*.}" # --> string.with.dots
##: Remove match until last occurrence
echo "${my_string##*.}" # --> dots
/n/n: Substitute one occurrence of the longest possible match
echo "${my_string/*./,}" # --> ,dots
//n/n: Substitute all occurrences of the longest possible match
echo "${my_string//?./,}" # --> exampl,strin,wit,dots
source: Baeldung