Bash String Operations

Bash String Operations

Parameter expansion allows you to expand a parameter and modify the value.

String length

1
2
3
4
$ str="The quick brown fox"
$ echo ${#str}
19

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
2
3
4
5
6
7
8
9
$ str='abc'
$ echo ${str}
abc

$ echo ${str^}
Abc

$ echo ${str^^}
ABC

To lower case

1
2
3
4
5
6
7
8
9
$ str='ABC'
$ echo ${abc}
ABC

$ echo ${str,}
aBC

$ echo ${str,,}
abc

String replace

replace first match. format is ${string/pattern/replacement}. see example

1
2
3
4
5
6
7
$ str="foo foo bar"

$ echo ${str/foo/baz}
baz foo bar

$ echo ${str/f*o/baz}
baz bar

replace all matches. format is ${string//pattern/replacement}. see example

1
2
$ echo ${str//foo/baz}
baz baz bar

replace from the front. format is ${string/#pattern/replacement}. see example

1
2
$ echo ${str/#foo/baz}
baz foo bar

replace from the back. format is ${string/%pattern/replacement}. see example

1
2
$ echo ${str/%bar/baz}
foo foo baz

SubString

format

1
2
${string:position}
${string:position:length}

example

1
2
3
4
5
6
7
$ str="The quick brown fox"

$ echo ${str:4}
quick brown fox

$ echo ${str:4:5}
quick

Indexof

format is expr index "$string" $substring

1
2
3
4
$ str="foo foo bar"

$ expr index "$str" bar # find index of 'bar'
9

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
2
3
4
5
6
7
8
9
10
11
12
13
$ FILE="myFile.tar.gz"

$ echo ${FILE%.*}
myFile.tar

$ echo ${FILE%%.*}
myFile

$ echo ${FILE#*.}
tar.gz

$ echo ${FILE##*.}
gz

Reference