Bash String Operations
Bash String Operations
Parameter expansion allows you to expand a parameter and modify the value.
String length
1 | $ str="The quick brown fox" |
Upper case and Lower case
This feature is avaiable on Bash version 4.0 or above. use echo $BASH_VERSION
command to get bash version.
To upper case
1 | $ str='abc' |
To lower case
1 | $ str='ABC' |
String replace
replace first match. format is ${string/pattern/replacement}
. see example
1 | $ str="foo foo bar" |
replace all matches. format is ${string//pattern/replacement}
. see example
1 | $ echo ${str//foo/baz} |
replace from the front. format is ${string/#pattern/replacement}
. see example
1 | $ echo ${str/#foo/baz} |
replace from the back. format is ${string/%pattern/replacement}
. see example
1 | $ echo ${str/%bar/baz} |
SubString
format
1 | ${string:position} |
example
1 | $ str="The quick brown fox" |
Indexof
format is expr index "$string" $substring
1 | $ str="foo foo bar" |
Trim
Format
- ${variable%pattern} Trim the shortest match from the end
- ${variable%%pattern} Trim the longest match from the end
- ${variable#pattern} Trim the shortest match from the beginning
- ${variable##pattern} Trim the longest match from the beginning
Example to extract filename and extension
1 | $ FILE="myFile.tar.gz" |