${} in shell

Introduction

${} (parameter substitution) is a useful way to manipulate strings in shell

it can print out the length of a string, just like len() function in python

1
2
3
string="hello"
echo ${#string}
→ 5

More:

  • # : Delete the left part
  • % : Delete the right part
  • Single symbol means minimum matching
  • Double symbol means maxmun matching

Extract from string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
str="/dir1/dir2/my.file.txt"

# remove the first "/" and it\'s left part
echo ${str#*/}
→ dir1/dir2/my.file.txt

# remove last "/" and it\'s left part
echo ${str##*/}
→ my.file.txt

# remove the first "." and it\'s left part
echo ${str#*.}
→ file.txt

# remove last "." and it\'s left part
echo ${str##*.}
→ txt

echo ${str%/*}
→ /dir1/dir2
echo ${str%%/*}
→ (null)
echo ${str%.*}
→ /dir1/dir2/my.file
echo ${str%%.*}
→ /dir1/dir2/my

Based on character position

1
${str:m:n}
  • m : start position
  • n : end position
1
2
3
4
5
6
str="/dir1/dir2/my.file.txt"

echo ${str:0:5}
→ /dir1
echo ${str:5:5}
→ /dir2

Replace string

1
2
${str/A/B}
${str//A/B}
  • replace A with B
1
2
3
4
5
6
7
8
9
str="/dir1/dir2/my.file.txt"

# replace the first "dir" with "path"
echo ${str/dir/path}
→ /path1/dir2/my.file.txt

# replace all "dir" with "path"
echo ${str//dir/path}
→ /path1/path2/my.file.txt

Advanced

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
str="/dir1/dir2/my.file.txt"

# replace the head "dir" with "path"
echo ${str/#dir/path}
→ /dir1/dir2/my.file.txt # No change
# reassign str
str="dir0/dir1/dir2/my.file.txt"
echo ${str/#dir/path}
→ path0/dir1/dir2/my.file.txt

# replace the ending "dir" with "path"
echo ${str/%dir/path}
→ dir0/dir1/dir2/my.file.txt
echo ${str/%txt/conf}
→ dir0/dir1/dir2/my.file.conf
Author: kwin
Link: https://blog.kwin.win/2020/04/24/${}-in-shell/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.